[英]How to convert list of dicts to dicts?
I have a list of dict that I am struggling to change to list of dicts:我有一个 dict 列表,我正在努力将其更改为 dicts 列表:
x = [
{ # begin first and only dict in list
'11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
, '22': [{'bb': '824', 'cc': '19'}]
}
]
Which currently has a length of 1. ie:当前长度为1。即:
print(len(x)) # 1
I intend to change it to list of dicts.我打算将其更改为字典列表。 ie:
IE:
desired = [
{ # begin first dict in list
'11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
}
, { # begin second dict in list
'22': [{'bb': '824', 'cc': '19'}]
}
]
print(len(desired)) # 2
What I tried:我尝试了什么:
dd = {}
for elem in x:
for k,v in elem.items():
dd[k] = v
print([dd])
print(len(dd)) # 2
Is there a better way or perhaps more efficient way?有没有更好的方法或更有效的方法?
Like others mentioned, there is nothing "wrong" with what you've tried.就像其他人提到的那样,您的尝试没有任何“错误”。 However, you might be interested in trying a list comprehension:
但是,您可能有兴趣尝试列表推导:
x_desired = [{k: v} for i in x for k, v in i.items()]
Like your attempted approach, this is effectively 2 for loops, the second nested within the first.就像您尝试的方法一样,这实际上是 2 个 for 循环,第二个嵌套在第一个循环中。 In general, list comprehensions are considered fast and Pythonic.
一般来说,列表推导被认为是快速和 Pythonic 的。
Do you want the result to be 2
as you"ve got two keys ( 11
& 22
)? then try this:您是否希望结果为
2
,因为您有两个键( 11
和22
)?然后试试这个:
print(len(x[0]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.