简体   繁体   English

我想从字典元素创建列表

[英]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.

相关问题 我有两个列表,我想从中创建一个字典。 但是我想为一个键存储多个值 - I have two list and I want to create a dictionary from it . But I want to store multiple values for one key 如何基于字典中的元素创建列表? - How to create list based on elements from dictionary? 从Python中的列表元素创建字典 - Create dictionary from list elements in Python 从元素对列表创建字典 - create a dictionary from a list of pairs of elements 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素? - How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one? 我想以复杂的方式从数据列表中获取字典列表? - I want to get a list of dictionary from a list of data in a complex way? 我想创建一个列表的元素,其中每个元素都来自一个满意的嵌套 for if 循环语句 - I want to create elements of a list where each element comes from a satisfied nested for if loop statement 我如何创建一个包含列表元素的特定字符串的字典? - How could I create a dictionary taking specific strings of elements of a list? 使用具有多个级别的列表中的元素创建字典 - Using elements from a list with many levels to create a dictionary 如何用字典中的可选元素列表创建对象? - How to create objects with a list of optional elements from a dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM