如何把(一号的)清单变成字典



我有一个字典列表,在字典中有字典,在这些字典中,有作为值的列表——在这些列表中是我需要访问的信息。

我想把这些清单变成字典。整个字典列表是这样设置的:

data = [{'date': 'Aug 1 1980', 
'hour': '2PM', 
'group': {'location' : 
[{'country': 'United States', 
'state': 'Utah', 
'city': 'St. George', 
'coordinates': [37.0965, 113.5684]}]},
{'date': 'Aug 1 1980', 
'hour': '4PM', 
'group': {'location' : 
[{'country': 'United States', 
'state': 'Utah', 
'city': 'St. George', 
'coordinates': [37.0965, 113.5684]}]}]

我需要坐标,但位置类型是列表。我怎样才能把这个列表变成字典?我应该先按":"one_answers","拆分为键和值吗?这似乎是一种糟糕的方法,我希望有人能帮助我找到一种更好、更快的方法。

编辑我希望我的字典看起来像这样:

{'country': 'United States', 'state': 'Utah', 'city' :'St George', 'coordinates': [37.0965, 113.5684]}

我认为以下内容符合您的要求(尽管我不完全确定,因为我必须修复您的输入数据以使其有效,并猜测您到底希望得到什么结果。

from pprint import pprint
data = [{'date': 'Aug 1 1980',
'hour': '2PM',
'group': {'location': [{'country': 'United States',
'state': 'Utah',
'city': 'St. George',
'coordinates': [37.0965, 113.5684]}]}},
{'date': 'Aug 1 1980',
'hour': '4PM',
'group': {'location': [{'country': 'United States',
'state': 'Utah',
'city': 'St. George',
'coordinates': [37.0965, 113.5684]}]}}]
fixed_data = []
for dct in data:
dct['group']['location'] = dct['group']['location'][0]
fixed_data.append(dct)
pprint(fixed_data, sort_dicts=0)

打印结果:

[{'date': 'Aug 1 1980',
'hour': '2PM',
'group': {'location': {'country': 'United States',
'state': 'Utah',
'city': 'St. George',
'coordinates': [37.0965, 113.5684]}}},
{'date': 'Aug 1 1980',
'hour': '4PM',
'group': {'location': {'country': 'United States',
'state': 'Utah',
'city': 'St. George',
'coordinates': [37.0965, 113.5684]}}}]

最新更新