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