[英]iterate list of dictionary and append python
我有一个词典列表(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])
对于此用例/查询,您拥有的数据结构不太方便。 如果您不能更改数据结构,这是一个幼稚的解决方案:
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]
我不确定您要尝试什么,但是为了达到您的目标,我尽可能少地修改了您的示例:
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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.