[英]How to turn a list (of size one) into a dictionary?
I have a list of dictionaries, and within the dictionaries there are dictionaries, and within those dictionaries, there are lists as values - within those lists is the information I need to access.我有一个字典列表,在字典中有字典,在这些字典中,有列表作为值 - 在这些列表中是我需要访问的信息。
I want to turn the lists into dictionaries.我想把列表变成字典。 The entire list of dictionaries are set up like this:
整个字典列表设置如下:
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]}]}]
I need the the coordinates but the type of location is a list.我需要坐标,但位置类型是一个列表。 How can I turn this list into a dictionary?
我怎样才能把这个列表变成字典? Should I start by splitting by ':' and ','s into keys and values?
我应该首先将 ':' 和 ',' 拆分成键和值吗? That seems like an awful way to do it and I'm hoping someone can help me with a better, quicker way.
这似乎是一种糟糕的方法,我希望有人能以更好、更快的方式帮助我。
Edit I would want my dictionary to look like this:编辑我希望我的字典看起来像这样:
{'country': 'United States', 'state': 'Utah', 'city' :'St George', 'coordinates': [37.0965, 113.5684]}
I think the following does what you want (although I'm not totally sure since I had to fix your input data to make it valid and guess a little on what exactly you wanted the result to be.我认为以下内容可以满足您的需求(尽管我不完全确定,因为我必须修复您的输入数据以使其有效并猜测您想要的结果到底是什么。
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)
Printed result:打印结果:
[{'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]}}}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.