我有一些这样的数据:
{'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 值:
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,您还可以保存包含缩写的字典,或将其返回。
