我有一个词典列表:
[
{"START":"Denver", "END":"Chicago", "Num":0},
{"START":"Dallas", "END":"Houston", "Num":3},
{"START":"Virginia", "END":"Boston", "Num":1},
{"START":"Washington", "END":"Maine", "Num":7}
]
如何以大多数pythonic方式访问此列表中具有"START":"Virginia", "END":"Boston"
的字典?
答案 0 :(得分:8)
最恐怖的方式可能是列表理解:
[ d for d in dict_list if d["START"] == "Virginia" and d["END"] == "Boston" ]
正如mgilson指出的那样,如果您假设列表中只有一个项目位于该对位置,则可以使用next
使用相同的生成器表达式而不是括号。这将只返回匹配的dict,而不是包含它的单项列表:
trip = next( d for d in dict_list
if d["START"] == "Virginia" and d["END"] == "Boston" )
无论哪种方式,结果都引用与原始列表相同的dict对象,因此您可以进行更改:
trip["Num"] = trip["Num"] + 1
当通过原始列表访问时,这些更改将会存在:
print(dict_list[2]["Num"]) # 2
正如Ashwini Chaudhary在回答中指出的那样,你的搜索本身可能被指定为词典。在这种情况下,生成器表达式中的if
条件稍有不同,但逻辑是相同的:
search = { "START": "Virginia", "END": "Boston" }
trip = next(d for d in dict_list if all(i in d.items() for i in search.items()))
答案 1 :(得分:2)
将all()
与dict.items()
:
In [66]: lis=[
....: {"START":"Denver", "END":"Chicago", "Num":0},
....: {"START":"Dallas", "END":"Houston", "Num":3},
....: {"START":"Virginia", "END":"Boston", "Num":1},
....: {"START":"Washington", "END":"Maine", "Num":7}
....: ]
In [67]: for x in lis:
....: if all(y in x.items() for y in search.items()):
....: x['Num']="foobar" #change Num here
....:
In [68]: lis
Out[68]:
[{'END': 'Chicago', 'Num': 0, 'START': 'Denver'},
{'END': 'Houston', 'Num': 3, 'START': 'Dallas'},
{'END': 'Boston', 'Num': 'foobar', 'START': 'Virginia'},
{'END': 'Maine', 'Num': 7, 'START': 'Washington'}]
使用list comprehension
:
In [58]: [x for x in lis if all(y in x.items() for y in search.items())]
Out[58]: [{'END': 'Boston', 'Num': 1, 'START': 'Virginia'}]
答案 2 :(得分:2)
如果您要进行多次搜索,并且您知道每对位置都有一个且只有一个dict,您可以从列表中创建一个dict,如下所示:
d = dict(((x['START'], x['END']), x) for x in list_of_dicts)
然后就像这样在新词典中进行查找:
found_dict = d[('Virginia', 'Chicago')]
您可以随时更改found_dict
。
答案 3 :(得分:1)
如果每个项目都是唯一的,那么您可以这样做:
def get_dict(items, start, end):
for dict in items:
if dict['START'] == start and dict['END'] == end:
return dict
然后:
>>> items = [
{"START":"Denver", "END":"Chicago", "Num":0},
{"START":"Dallas", "END":"Houston", "Num":3},
{"START":"Virginia", "END":"Boston", "Num":1},
{"START":"Washington", "END":"Maine", "Num":7}
]
>>> get_dict(items, 'Virginia', 'Boston')
{"START":"Virginia", "END":"Boston", "Num":1}
这很简单,但我认为为了完整起见我会发布它。