将字典列表中的值添加到单独的列表中,并查找/计算常用值

时间:2016-03-24 18:08:10

标签: list python-2.7 dictionary

我有一个包含这样字典的列表:

[{"abc":"da123-tap","efg":"xyzf","acd":"123-brf"}, {"abc":"ab234-tap","efg":"yuvi","acd":"345-brf"}]  

我希望列表中的abc的所有值(list1)和efg的所有值都列在另一个列表中(list2)。

更新问题:

我读了一个文件来获取这个词典列表:

[{"Sample":"da123-tap","Name":"john","dof":"Date(304239600000)","Account":"Clinic1"},
{"Sample":"da456-tap-tap","Name":"smith","dof":"Date(304239600000)","Account":"Clinic2"},
{"Sample":"da678-tap-tap","Name":"jane","dof":"Date(304239600000)","Account":"Clinic1"},
{"Sample":"da987-tap-tap","Name":"doe","dof":"Date(304239600000)","Account":"Clinic2"}]

查找

  1. Sample
  2. list1的值
  3. Account
  4. list2的值
  5. 计算属于Sample
  6. Clinic1的值
  7. 计算属于Sample
  8. Clinic2的值

1 个答案:

答案 0 :(得分:0)

仅出于教育原因,将不同键的值导入多个列表的优雅方法可能是使用zip()并解压缩:

>>> l = [
...     {"abc":"da123-tap","efg":"xyzf","acd":"123-brf"}, 
...     {"abc":"ab234-tap","efg":"yuvi","acd":"345-brf"}
... ]
>>> 
>>> a, b = zip(*[(item["abc"], item["efg"]) for item in l])
>>> print(a)
('da123-tap', 'ab234-tap')
>>> print(b)
('xyzf', 'yuvi')