将平面 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' ... }
将其解析为以下格式的字典列表的最Pythonic方法是什么:
[{'item1':'a', 'item2':'34'},
{'item1':'sd', 'item2':'2', 'item3':'fg'},
{'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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出将是预期的:
and the output will be the expected:
我会使用字典的中间字典,因为无法知道末尾有多少“行”,并且以后无法在列表末尾插入新元素。
它应该足够简单,可以迭代此 dict 中的每个元素并将其解析为行号和键。然后,您可以轻松地将新的
dict
传输到您想要的列表中。一个可能的实现可能是:I'd go with an intermediate dictionary of dictionaries, since there is no way of knowing how many "lines" you'd have at the end and you can't insert a new element at the end of the list later.
It should be simple enough to iterate over every element in this
dict
and parse it into the line number and key. You could then easily transfer the newdict
into the list you desired. A possible implementation could be: