2024-10-02 10:33:38 发布
网友
我有这样一些数据:
{'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
从我对Python所知甚少的情况来看,这看起来像是一本字典中的字典。你知道吗
但不管怎样,我怎么能用“NY”作为键来获取“New York”的值呢?你知道吗
它是一个有一个键值对的字典。该值是字典列表。你知道吗
d = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
要查找缩写的name,您应该遍历列表中的词典,然后比较abbrev-值是否匹配:
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,您还可以保存包含缩写的字典,或者返回它。你知道吗
print
使用^{}并根据'abbrev'键筛选子词典:
'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
print(newd['NY'])
一旦建立了字典,您就可以以很快的查找速度重复使用它。在需要时从原始数据集构建其他专用词典。你知道吗
它是一个有一个键值对的字典。该值是字典列表。你知道吗
要查找缩写的
name
,您应该遍历列表中的词典,然后比较abbrev
-值是否匹配:除了
print
,您还可以保存包含缩写的字典,或者返回它。你知道吗使用^{} 并根据
'abbrev'
键筛选子词典:输出:
当你有一个数据集不适合你的需要,而不是使用它“原样”,你可以建立另一个字典,使用字典理解与键/值作为你的子字典的值,使用固定键。你知道吗
结果:
当然:
print(newd['NY'])
产生New York
一旦建立了字典,您就可以以很快的查找速度重复使用它。在需要时从原始数据集构建其他专用词典。你知道吗
相关问题 更多 >
编程相关推荐