【问题标题】:Using items in a list as dictionary keys使用列表中的项目作为字典键
【发布时间】:2014-02-09 20:27:44
【问题描述】:

所以我有一本名为“useraccounts”的字典。我设法通过执行以下操作获取字典中第 12 类中项目的所有键:

found = ([k for k in useraccounts if useraccounts[k]['class'] == '12'])

返回的列表是:

['bob', 'terry'] 

这是正确的。现在无论如何我可以将这些结果作为键,然后单独使用它们来单独打印字典中的相关信息。比如获取程序打印结果:

useraccounts[THE_KEYS_FOUND_IN_THE_LIST]['totalscore']

非常感谢任何帮助。

提前致谢。

【问题讨论】:

    标签: python list python-3.x dictionary


    【解决方案1】:

    我想你想要这样的东西:

    for name in found:
        print(name, useraccounts[name]['totalscore'])
    

    【讨论】:

      【解决方案2】:

      您可以在以前的基础上继续发展:

      scores = [useraccounts[k]['totalscore'] for k in useraccounts if useraccounts[k]['class'] == '12']
      # scores = [ list of scores ]
      

      【讨论】:

        【解决方案3】:

        如果您只想要这些特定键的总分:

        totals = [(key,value['totalscore') for key, value in useraccounts.items() if value['class'] == '12']
        

        【讨论】:

          猜你喜欢
          • 2013-01-26
          • 2021-02-09
          • 2023-03-27
          • 1970-01-01
          • 2020-08-04
          • 1970-01-01
          • 2019-12-04
          • 2020-04-30
          • 2014-10-10
          相关资源
          最近更新 更多