![](/img/trans.png)
[英]How do I convert a list of dictionaries to a dictionary of lists in Python?
[英]How do I convert a list of lists to a python dictionary of the following format?
我目前有以下类型的列表:
[["'Person':Yiyang Chen,'Message':10"], ["'Person':Junbo Sheng,'Message':2"], ["'Person':Jiayi Lin,'Message':4"], ["'Person':Baitong Liu,'Message':8"], ["'Person':Zian Fan,'Message':9"]]
我正在尝试将此列表列表转换为 python 字典,该字典必须写入(json.dumps)到 JSON output 文件中,如下所示:
[{"Person":"John Smith","Message":8},…]
我如何实现这一目标?
对于类型列表的列表 -
cars_list = [[1,'Honda','red'], [2,'Toyota','white'], [3,'Mazda','blue']]
我了解使用以下代码有效-
cars_dict = {}
for key, car, color in cars_list:
cars_dict[key] = [car, color]
- 但由于现有的 a:b, c:d 格式,我无法将以前的列表列表操作为我想要获取的格式
编辑:这是我编写的代码,它给了我列表的结果列表:
f = open("input.txt", "r")
# d = defaultdict(int)
keylist = []
final_use = []
for line in f:
lineslist = line.split()
nameslist = lineslist[1:3]
nameslist = [s.replace(':', '') for s in nameslist]
keylist.append(nameslist[0]+" "+nameslist[1])
# print(keylist)
d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in keylist]
# print(d)
for person in d:
final_use.append(["'Person':"+str(person)+","+"'Message':"+str(d[person])])
print(final_use)
此代码的示例 output 是我在开头附加的列表列表
样品 output:
[["'Person':Yiyang Chen,'Message':10"], ["'Person':Junbo Sheng,'Message':2"], ["'Person':Jiayi Lin,'Message':4"], ["'Person':Baitong Liu,'Message':8"], ["'Person':Zian Fan,'Message':9"]]
以下是 input.txt 中存在的数据示例:(不包括整个数据,因为它是一个巨大的文件)注意:条目之间有空行
00:01:44 陈奕扬:你好
00:01:46 盛俊博:早上好
00:01:46 林嘉怡:1
00:01:47 刘柏彤:是的,email 我
00:01:47 子凡:下午批
00:01:48 莱昂·吕克:1
00:01:48 王志谦:1
00:01:49 嘉会路:1
00:01:49 陈世明:1
00:07:47 姜艳茹:1
这是关于什么的描述:这是我正在尝试操作的缩放聊天的示例。 我正在使用这个 input.txt 文件并尝试 output 一个 JSON 文件,该文件显示人名和该人在缩放聊天中的聊天次数,格式如下:(示例格式)
[{"Person":"John Smith","Message":8},
{"Person":"Yiyang Chen","Message":10},
{"Person":"Junbo Sheng","Message":2}…]
我希望这现在更清楚了。 另外,我知道我的代码不是很干净,因为我是初学者,希望您能提供帮助。
提前致谢。
实际上,您有一个列表列表,其中内部列表包含一个字符串。 由于该字符串的格式很简单,您可以使用正则表达式来解析它并用它提供字典。 演示:
import re
import pprint
ll = [["'Person':Yiyang Chen,'Message':10"], ["'Person':Junbo Sheng,'Message':2"],
["'Person':Jiayi Lin,'Message':4"], ["'Person':Baitong Liu,'Message':8"],
["'Person':Zian Fan,'Message':9"]]
rx = re.compile(r"\s*'Person'\s*:\s*(.*?)\s*,\s*'Message'\s*:\s*(.*)\s*$")
d = [{'Person': m.group(1), 'Message': m.group(2)}
for m in [rx.match(i[0]) for i in ll]]
pprint.pprint(d)
按预期给出:
[{'Message': '10', 'Person': 'Yiyang Chen'},
{'Message': '2', 'Person': 'Junbo Sheng'},
{'Message': '4', 'Person': 'Jiayi Lin'},
{'Message': '8', 'Person': 'Baitong Liu'},
{'Message': '9', 'Person': 'Zian Fan'}]
但是在看到您构建列表列表的方式之后,直接构建字典列表会简单得多。 您只需稍微更改脚本的结尾:
...
# print(d)
for person in d:
final_use.append({'Person': person, 'Message': d[person])})
print(final_use)
而final_use
可以直接用于生成JSON字符串或文件...
这是我的建议,使用 function 将列表中的每个项目转换为所需的字典:
l=[["'Person':Yiyang Chen,'Message':10"], ["'Person':Junbo Sheng,'Message':2"], ["'Person':Jiayi Lin,'Message':4"], ["'Person':Baitong Liu,'Message':8"], ["'Person':Zian Fan,'Message':9"]]
def f(x):
x2=x[0]
x3=x2.split(',')
x4={i.split(':')[0][1:-1]:int(i.split(':')[1]) if i.split(':')[1].isdigit() else i.split(':')[1] for i in x3}
return x4
res=[f(i) for i in l]
打印(分辨率)
Output:
[{'Person': 'Yiyang Chen', 'Message': 10}, {'Person': 'Junbo Sheng', 'Message': 2}, {'Person': 'Jiayi Lin', 'Message': 4}, {'Person': 'Baitong Liu', 'Message': 8}, {'Person': 'Zian Fan', 'Message': 9}]
原始代码的主要问题是您试图将结构化数据表示为字符串。 然后,您随后尝试将其转换回可用数据。
正如您所遇到的,这变得非常麻烦,因为您正在创建非标准格式并尝试在后续步骤中对其进行解析。
相反,您可以做的是在整个代码中以结构化的方式存储数据。
一种方法是将问题分解为两个步骤:
下面,我使用collections.defaultdict
来统计每个用户发送的消息数。
然后,我使用列表推导将其转换为字典列表。
您还可以通过使用str.split
的maxsplit
参数来稍微清理数据提取。
import collections
counts = collections.defaultdict(int)
with open('input.txt') as f:
for line in f:
# first, remove the unwanted colon from the line
line = line.replace(':', '')
# next, split the line up (at most 3 splits)
# we "discard" the first & last fields, and keep only the middle two (first & last name)
_, first, last, _ = line.split(maxsplit=3)
# increment the number of messages for this user
# using an f-string to combine the two names into a string that can be used as a key
counts[f'{first} {last}'] += 1
# now, loop through the key-value pairs, and convert each into a dict (rather than a string representation)
result = [{'Person': k, 'Messages': v} for k, v in counts.items()]
本质上,此版本遵循与您的原始版本相同的模式,除了第一部分要简单得多,并且您的最终循环被替换为列表推导式,该列表推导式创建字典列表,而不是嵌套的字符串列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.