[英]I want to create list from dictionary elements
I have Nested dictionary something like this.我有这样的嵌套字典。
{'A': {'21-26': 2,
'26-31': 7,
'31-36': 3,
'36-41': 2,
'41-46': 0,
'46-51': 0,
'Above 51': 0},
'B': {'21-26': 2,
'26-31': 11,
'31-36': 5,
'36-41': 4,
'41-46': 1,
'46-51': 0,
'Above 51': 3}}
And I want to create list by key from second dictionary.我想从第二个字典中按键创建列表。 And i don't want duplicates in my list.
而且我不想在我的列表中重复。
Required Output is所需输出为
ls = ['21-26','26-31','31-36','36-41','41-46','46-51','Above 51']
Thank you for your time and consideration.感谢您的时间和考虑。
You can use:您可以使用:
>>> list(set(key for val in d.values() for key in val.keys()))
['21-26', '36-41', '31-36', '46-51', 'Above 51', '26-31', '41-46']
Where d
is your dictionary.其中
d
是您的字典。
Simple set comprehension, then convert to list.简单的集合理解,然后转换为列表。
a
is your dict. a
是你的字典。
list({k for v in a.values() for k in v.keys()})
Output ordering is random, but you can sort how you like.输出顺序是随机的,但您可以按照自己的喜好进行排序。
Can you use pandas?你能用熊猫吗? IF so:
如果是这样的话:
import pandas as pd
a = {'A': {'21-26': 2, '26-31': 7, '31-36': 3, '36-41': 2, '41-46': 0, '46-51': 0, 'Above 51': 0}, 'B': {'21-26': 2, '26-31': 11, '31-36': 5, '36-41': 4, '41-46': 1, '46-51': 0, 'Above 51': 3}}
pd.DataFrame(a).index.to_list()
output:输出:
['21-26', '26-31', '31-36', '36-41', '41-46', '46-51', 'Above 51']
You can use chain.from_iterable()
to chain inner dictionaries and dict.fromkeys()
to remove duplicates:您可以使用
chain.from_iterable()
来链接内部字典并使用dict.fromkeys()
来删除重复项:
from itertools import chain
c = chain.from_iterable(dct.values())
result = list(dict.fromkeys(c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.