将平面Python字典转换为字典列表 [英] Converting flat Python Dictionary to List of Dictionaries

查看:173
本文介绍了将平面Python字典转换为字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的字典,我不知道要接收的行数或项目数:

  {'line(0).item1':'a','line(0).item2':'34',
'line(1).item1':'sd','line (1).item2':'2','line(1).item3':'fg',
'line(2).item1':'f'...}

最简单的方法是将其解析成以下格式的字典列表:

  [{'item1':'a','item2':'34'},
{'item1':'sd','item2 ':'2','item3':'fg'},
{'item1':'f',...},...]
pre>

提前感谢

解决方案

  d = {'line(0).item1':'a'...} 

out = collections.defaultdict(list)
for k,v in d。 items():
n,val = re.findall(r'^ line\((\d +)\)\。(\w +)$',k)[0]
出[INT(N)]。一个pp((val,v))

my_list = [dict(out [v])for v in sorted(out)]

,输出将是预期的:

  [{'item2' :'34','item1':'a'},{'item2':'2','item3':'fg','item1':'sd'},{'item1':'f'}] 


I have a dictionary in the following format where I don't know the number of lines or items I'm going to receive:

{'line(0).item1':'a', 'line(0).item2':'34', 
 'line(1).item1':'sd', 'line(1).item2':'2', 'line(1).item3':'fg', 
 'line(2).item1':'f' ... }

What is the most pythonic way to parse this into a list of dictionaries in the following format:

[{'item1':'a', 'item2':'34'}, 
 {'item1':'sd', 'item2':'2', 'item3':'fg'}, 
 {'item1':'f',...}, ...]

Thanks in advance.

解决方案

d = {'line(0).item1':'a' ...}

out = collections.defaultdict(list)
for k,v in d.items():
    n,val = re.findall(r'^line\((\d+)\)\.(\w+)$', k)[0]
    out[int(n)].append((val,v))

my_list = [dict(out[v]) for v in sorted(out)]

and the output will be the expected:

[{'item2': '34', 'item1': 'a'}, {'item2': '2', 'item3': 'fg', 'item1': 'sd'}, {'item1': 'f'}]

这篇关于将平面Python字典转换为字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆