在词典中查找词典的值

2024-10-02 10:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一些数据:

{'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}

从我对Python所知甚少的情况来看,这看起来像是一本字典中的字典。你知道吗

但不管怎样,我怎么能用“NY”作为键来获取“New York”的值呢?你知道吗


Tags: 数据namenew字典情况bostonboyork
3条回答

它是一个有一个键值对的字典。该值是字典列表。你知道吗

d = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}

要查找缩写的name,您应该遍历列表中的词典,然后比较abbrev-值是否匹配:

for city in d['cities']:        # iterate over the inner list
    if city['abbrev'] == 'NY':  # check for a match
        print(city['name'])     # print the matching "name"

除了print,您还可以保存包含缩写的字典,或者返回它。你知道吗

使用^{}并根据'abbrev'键筛选子词典:

d = {'cities': [{'abbrev': 'NY', 'name': 'New York'},
                {'abbrev': 'BO', 'name': 'Boston'}]}

city_name = next(city['name'] for city in d['cities']
                 if city['abbrev'] == 'NY')

print city_name

输出:

New York

当你有一个数据集不适合你的需要,而不是使用它“原样”,你可以建立另一个字典,使用字典理解与键/值作为你的子字典的值,使用固定键。你知道吗

d = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
newd = {sd["abbrev"]:sd["name"] for sd in d['cities']}
print(newd)

结果:

{'NY': 'New York', 'BO': 'Boston'}

当然:print(newd['NY'])产生New York

一旦建立了字典,您就可以以很快的查找速度重复使用它。在需要时从原始数据集构建其他专用词典。你知道吗

相关问题 更多 >

    热门问题