3

我有一个字典列表:

[
{"START":"Denver", "END":"Chicago", "Num":0},
{"START":"Dallas", "END":"Houston", "Num":3},
{"START":"Virginia", "END":"Boston", "Num":1},
{"START":"Washington", "END":"Maine", "Num":7}
]

如何访问此列表中"START":"Virginia", "END":"Boston"以大多数 Python 方式具有的字典?

4

4 回答 4

8

最 Pythonic 的方式可能是列表推导:

[ d for d in dict_list if d["START"] == "Virginia" and d["END"] == "Boston" ]

正如 mgilson 指出的那样,如果您假设列表中只有一个项目具有该对位置,则可以使用next相同的生成器表达式,而不是括号。这将只返回匹配的字典,而不是包含它的单项列表:

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()))
于 2013-01-16T19:24:11.177 回答
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'}]
于 2013-01-16T19:24:15.763 回答
2

如果您要进行多次搜索,并且您知道每对位置只有一个字典,您可以从列表中创建一个字典,如下所示:

d = dict(((x['START'], x['END']), x) for x in list_of_dicts)

然后像这样在新的字典中进行查找:

found_dict = d[('Virginia', 'Chicago')]

您可以根据found_dict需要进行更改。

于 2013-01-16T19:44:02.657 回答
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}

这很简单,但为了完整起见,我想我会发布它。

于 2013-01-16T19:25:47.010 回答