【问题标题】:How to dump/append all the values of a dict into a list if key is a tuple?如果键是元组,如何将字典的所有值转储/附加到列表中?
【发布时间】:2011-07-20 09:47:34
【问题描述】:

我有一个列表中包含单元名称和测试名称的字典,如下所示:

dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}  
units = ['unit1', 'unit2']  
testnames = ['test1','test2'] 

我们如何将say test1 的所有值附加到一个列表中? 即

temp = [10,78] # test1 values
temp2 = [2,45] # test2 values

【问题讨论】:

  • 您不断发布具有相同数据的类似问题。你想从答案中学习吗?
  • @eumiro:嗨,我正在处理大量数据以生成统计数据。研究将它们排列成数据结构的不同/最佳方法。有人建议:{(tuple),value} 最好,但有人说 {x:{y:z}} 形式更好。通过与我的“多线”代码进行比较来查看并学习所有可能的方法。 :) 请裸露!谢谢..

标签: python list dictionary append tuples


【解决方案1】:

temp = [ j for i, j in dictA.iteritems() if "test1" in i ]

【讨论】:

    【解决方案2】:

    您似乎在询问list comprehensions

    [v for k,v in dictA.iteritems() if k[1] == 'test1']
    

    会给你:

    [10, 78]
    

    同样:

    >>> [v for k,v in dictA.iteritems() if k[1] == 'test2']
    [2, 45]
    

    现在,key 是一个元组,我们在 if 子句中引用了该元素。

    【讨论】:

      【解决方案3】:

      我会将 dictA 变成一个 for that is dictionaries of dictionary - 通过转换或更好地以这种形式构造它

      dictA = {'unit1':{'test1': 10, 'test2': 2}, 'unit2': {'test1': 78, 'test2': 45}}
      

      然后

      temp = [dictA[x]['test1'] for x in units] 
      temp2 = [dictA[x]['test2'] for x in units]
      

      【讨论】:

      • 有帮助。谢谢。早些时候我有那种形式的字典,但是由于在字典中的值之间执行操作而更改为我的形式在我的形式中会更容易。 :)
      猜你喜欢
      • 2020-04-09
      • 2020-05-18
      • 2019-07-05
      • 2023-03-23
      • 2011-09-29
      • 2022-01-06
      • 2021-12-24
      • 2018-11-30
      相关资源
      最近更新 更多