Python 如何索引到字典中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4326658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to index into a dictionary?
提问by Harpal
I have a Dictionary below:
我在下面有一个字典:
colors = {
"blue" : "5",
"red" : "6",
"yellow" : "8",
}
How do I index the first entry in the dictionary?
如何索引字典中的第一个条目?
colors[0]will return a KeyErrorfor obvious reasons.
colors[0]将返回 aKeyError显而易见的原因。
采纳答案by Sven Marnach
Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i]and d.values()[i]or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)
字典在 Python 3.6 及以下版本的 Python 中是无序的。如果您不关心条目的顺序并希望通过索引访问键或值,则可以使用d.keys()[i]andd.values()[i]或d.items()[i]。(请注意,这些方法在 Python 2.x 中创建了所有键、值或项目的列表。因此,如果您多次需要它们,请将列表存储在变量中以提高性能。)
If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs
如果您确实关心条目的顺序,从 Python 2.7 开始,您可以使用collections.OrderedDict. 或使用对列表
l = [("blue", "5"), ("red", "6"), ("yellow", "8")]
if you don't need access by key. (Why are your numbers strings by the way?)
如果您不需要按键访问。(顺便说一下,为什么你的数字是字符串?)
In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDictanymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.
在 Python 3.7 中,普通字典是有序的,所以你不再需要使用OrderedDict(但你仍然可以 - 它基本上是相同的类型)。Python 3.6 的 CPython 实现已包含该更改,但由于它不是语言规范的一部分,因此您不能在 Python 3.6 中依赖它。
回答by Ignacio Vazquez-Abrams
You can't, since dictis unordered. you can use .popitem()to get an arbitrary item, but that will remove it from the dict.
你不能,因为它dict是无序的。您可以.popitem()用来获取任意项目,但这会将其从 dict 中删除。
回答by user3368835
actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:
实际上我找到了一个真正帮助我的新解决方案,如果您特别关心列表或数据集中某个值的索引,您可以将字典的值设置为该索引!:
Just watch:
只是看:
list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
dictionary[i] = counter
counter += 1
print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}
Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)
现在,通过哈希图的强大功能,您可以在恒定时间内提取您的条目的索引(也就是快得多)
回答by Raj Damani
Addressing an element of dictionary is like sitting on donkey and enjoy the ride.
对字典中的一个元素进行寻址就像坐在驴上享受骑行。
As rule of Python DICTIONARY is orderless
由于 Python DICTIONARY 的规则是无序的
If there is
如果有
dic = {1: "a", 2: "aa", 3: "aaa"}
Now suppose if I go like dic[10] = "b", then it will not add like this always
现在假设如果我这样做dic[10] = "b",那么它不会总是这样添加
dic = {1:"a",2:"aa",3:"aaa",10:"b"}
It may be like
它可能像
dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}
Or
或者
dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}
Or
或者
dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}
Or any such combination.
或任何此类组合。
So thumb rule is DICTIONARYis orderless!
所以拇指规则是DICTIONARY是无序的!
回答by Pasha
If anybody still looking at this question, the currently accepted answer is now outdated:
如果有人还在看这个问题,那么目前接受的答案现在已经过时了:
Since Python 3.7* the dictionaries are order-preserving, that is they now behave exactly as collections.OrderedDicts used to. Unfortunately, there is still no dedicated method to index into keys()/ values()of the dictionary, so getting the first key / value in the dictionary can be done as
由于 Python 3.7* 字典是顺序保留的,也就是说,它们现在的行为与collections.OrderedDict过去完全一样。不幸的是,仍然没有专门的方法来索引字典的keys()/ values(),因此可以像这样获取字典中的第一个键 / 值
first_key = list(colors)[0]
first_val = list(colors.values())[0]
or alternatively (this avoids instantiating the keys view into a list):
或者(这样可以避免将键视图实例化为列表):
def get_first_key(dictionary):
for key in dictionary:
return key
raise IndexError
first_key = get_first_key(colors)
first_val = colors[first_key]
If you need an n-th key, then similarly
如果您需要n-th 键,则类似
def get_nth_key(dictionary, n=0):
if n < 0:
n += len(dictionary)
for i, key in enumerate(dictionary.keys()):
if i == n:
return key
raise IndexError("dictionary index out of range")
(*CPython 3.6 already included ordered dicts, but this was only an implementation detail. The language specification includes ordered dicts from 3.7 onwards.)
(*CPython 3.6 已经包含了有序的字典,但这只是一个实现细节。语言规范从 3.7 开始包括有序的字典。)
回答by Godfreyluck
oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!
哦,这是一个艰难的。基本上,您在这里拥有的是每个项目的两个值。然后你试图用一个号码作为键来打电话给他们。不幸的是,您的值之一已被设置为键!
Try this:
尝试这个:
colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}
Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.
现在您可以按编号调用键,就好像它们像列表一样被索引。您还可以通过它们在列表中的位置来引用颜色和数字。
For example,
例如,
colors[1][0]
// returns 'blue'
colors[3][1]
// returns '8'
Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.
当然,您将不得不想出另一种方法来跟踪每种颜色所在的位置。也许您可以拥有另一个字典来存储每种颜色的键作为其值。
colors_key = {'blue': 1, 'red': 6, 'yllow': 8}
颜色键 = {'蓝色':1,'红色':6,'黄色':8}
Then, you will be able to also look up the colors key if you need to.
然后,如果需要,您还可以查找颜色键。
colors[colors_key['blue']][0] will return 'blue'
colors[colors_key['blue']][0] 将返回 'blue'
Something like that.
类似的东西。
And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.
然后,当你在做它的时候,你可以用数字值作为键来做一个字典,这样你就可以随时使用它们来查找你的颜色,你知道,如果你需要的话。
values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}
值 = {5: [1, '蓝色'], 6: [2, '红色'], 8: [3, '黄色']}
Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.
然后, (colors[colors_key[values[5][1]]][0]) 将返回 'blue'。
Or you could use a list of lists.
或者您可以使用列表列表。
Good luck!
祝你好运!

