[英]Turn List of Dictionaries into Dictionary of Dictionaries with index
I have a list of dictionaries, like this:我有一个字典列表,如下所示:
ls_dict = [{'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'},
{'A': 65, 'B': 66, 'C': 67},
{'a': 97, 'b': 98, 'c': 99}]
Which produces this:产生这个:
[{'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, {'A': 65, 'B': 66, 'C': 67}, {'a': 97, 'b': 98, 'c': 99}]
What I want is a dictionary of dictionaries where each dictionary is indexed like the following:我想要的是一本字典,其中每个字典的索引如下:
{"0": {'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, "1": {'A': 65, 'B': 66, 'C': 67}, 2: {'a': 97, 'b': 98, 'c': 99}}
The additional problem is that I need to convert the former to the latter, rather than adapting my sample creation code, as I just spent 15 hours downloading the data into the current (wrong) format.另一个问题是我需要将前者转换为后者,而不是调整我的示例创建代码,因为我只花了 15 个小时将数据下载为当前(错误)格式。
Any suggestions?有什么建议么? Thank you.
谢谢你。
You can do with enumerate
,您可以使用
enumerate
,
In [75]: {str(index): lst for index, lst in enumerate(ls_dict)}
Out[75]:
{'0': {'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'},
'1': {'A': 65, 'B': 66, 'C': 67},
'2': {'a': 97, 'b': 98, 'c': 99}}
hello you need to do this whit for你好,你需要这样做
keyList = ['0','1','2']
valueList = [{'py': 'Python', 'mat': 'MATLAB', 'cs': 'Csharp'}, {'A': 65, 'B': 66, 'C': 67}, {'a': 97, 'b': 98, 'c': 99}]
d = {}
for i in range(len(keyList)):
d[keyList[i]] = valueList[i]
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.