简体   繁体   English

Python如何从字典中获取所有值相同的名称键

[英]Python How can I get all values same name keys from dictionary

>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}

It has same keys 'a' 它具有相同的键“ a”

and I want to get all values from this dic 我想从这个骰子中获取所有值

but when I use 但是当我使用

>>> dic.get('a')

It only returns 它只返回

['4a','5a']

How can I get all 'a' key's values from it? 如何从中获取所有“ a”键的值?

I have thought to using repetitive statement to check all keys, but it seems inefficient 我曾考虑过使用重复性语句来检查所有键,但是效率似乎很低

A dictionary can't store duplicate keys. 字典不能存储重复的键。 One way around is to store lists or sets inside the dictionary. 一种解决方法是将列表或集合存储在字典中。 I'd recommend you to store values in a set pointing same keys. 我建议您将值存储在指向相同键的集合中。

>>> from collections import defaultdict

>>> dic = defaultdict(list)

>>> dic['a'].extend(['1a','2a','3a'])
>>> dic['a'].extend(['4a','5a'])
>>> dic['b'].extend(['1b','2b'])

You say: 你说:

>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}
It has same keys 'a'

no it doesn't: 不,它不是:

>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}
>>> dic
{'a': ['4a', '5a'], 'b': ['1b', '2b']}

the first occurrence of key 'a' has simply disappeared, "trampled over" by the second occurrence of the same key. 第一次出现的键'a'已经消失了,而第二次出现了相同的键则“消失”了。

I doubt you're building dic as a dict literal like this (I think such a literal should raise an exception, because it makes absolutely no sense, but, alas, it doesn't) -- can you show us the actual code you're using instead in order to build that dict ? 我怀疑您是否将dic构建为这样的dict文字(我认为这样的文字应该引发异常,因为它绝对没有道理,但是,a,它没有)–您可以向我们展示实际的代码吗?而是为了构建该dict Then we might suggest how to actually build the dict you want!-) 然后我们可能会建议如何实际构建您想要的dict !-)

Python字典不支持重复键,请检查此线程以寻求解决方案, 在python中使用重复键制作字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 如何在字典中获取具有相同值的键/ - Python - How to get keys with same values in a dictionary/ 如何从字典 python 中获取键和值 - How to get keys and values from dictionary python 如何从另一个python字典中的一个字典中获得相应的列表值,在列表中它们被列为键,比较并打印出csv? - How can I get corresponding list values in one dictionary from another python dictionary where they are listed as keys, compare and print out a csv? Python,JSON。 如何从具有相同名称的键中获取值? - Python, JSON. How can I get a value from keys with the same name? python字典:如何获取具有特定值的所有键 - python dictionary: How to get all keys with specific values 如何在 Python 的 GUI 中打印字典中的所有值 - How can i print all values from a dictionary in a GUI in Python 如何从 Python 中的字典中提取所有值? - How can I extract all values from a dictionary in Python? 如何从同一数据框中的字典键创建具有键名的列? - How can I create column having key name from dictionary keys in same dataframe? 如何从Python中的嵌套字典中一起打印所有键和值? - How to print all the keys and values together from a nested dictionary in Python? 如何从指定值的字典中获取所有键? - How to get all keys from dictionary that specified values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM