迭代字典列表并追加python

时间:2016-03-23 14:32:22

标签: python python-2.7 dictionary

我有一个字典列表(a),我正在尝试遍历字典搜索特定值,如果字典有该值,则将该字典添加到新的字典集合中。到目前为止我已经

newList = {}

a = [{"one": "green", "two" : "blue", "three" : "red"},
     {"two": "blue", "four" : "green", "five" : "yellow"},
     {"two": "blue", "six": "white", "seven" : "black"}]

for index in range(len(a)):
 if a[index][?] = ["blue"]:
   newList.append(a[index])

2 个答案:

答案 0 :(得分:5)

您拥有的数据结构对于此用例/查询并不方便。如果您无法更改数据结构,这是一个天真的解决方案:

newList = [d for d in a if "blue" in d.values()]

请注意,if "blue" in d.values()查找为O(n),这是您在执行in查找时应尽量避免的。

在这种情况下,更合适的数据结构将是内部字典中的键和值交换的数据结构:

a = [{"green": "one", "blue": "two", "red": "three"},
     {"blue": "two":, "green": "four", "yellow": "five"},
     {"blue": "two", "white": "six", "black": "seven"}]

在这种情况下,您可以按键查看字典O(1)

newList = [d for d in a if "blue" in d]

答案 1 :(得分:1)

我不完全确定你在尝试什么,但我尽可能少地修改你的例子以实现你的目标:

ewList = []
a = [{"one": "green", "two": "blue", "three": "red"},
     {"two": "blue", "four" : "green", "five" : "yellow"},
     {"two": "yellow", "six": "white", "seven" : "black"}]

for d in a:
    if "yellow" in d.values():
        ewList.append(d)

print ewList

输出:

[{'four': 'green', 'five': 'yellow', 'two': 'blue'}, {'seven': 'black', 'six': 'white', 'two': 'yellow'}]