如何索引字典?

问题:如何索引字典?

我在下面有一个字典:

colors = {
    "blue" : "5",
    "red" : "6",
    "yellow" : "8",
}

如何索引字典中的第一个条目?

colors[0]KeyError由于明显的原因将返回。

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 KeyError for obvious reasons.


回答 0

在Python版本(包括Python 3.6)及更高版本中,字典是无序的。如果您不关心条目的顺序,并且仍然想通过索引访问键或值,则可以使用d.keys()[i]d.values()[i]d.items()[i]。(请注意,这些方法创建了Python 2.x中所有键,值或项的列表。因此,如果一次又一次需要它们,请将列表存储在变量中以提高性能。)

如果您确实关心条目的顺序,那么可以从Python 2.7开始使用collections.OrderedDict。或使用成对清单

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

如果您不需要通过密钥访问。(为什么您的数字是字符串?)

在Python 3.7中,常规字典是有序的,因此您不再需要使用它OrderedDict(但您仍然可以使用-它基本上是相同的类型)。Python 3.6的CPython实现已经包含了这一更改,但是由于它不是语言规范的一部分,因此您不能在Python 3.6中依赖它。

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.)

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

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 OrderedDict anymore (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.


回答 1

如果仍然有人在看这个问题,那么当前接受的答案现在已经过时了:

由于Python 3.7 *字典是顺序保留的,也就是说它们现在的行为与collections.OrderedDicts完全相同。不幸的是,仍然没有专用的方法可以索引到字典的keys()/values()中,因此可以通过以下方法获取字典中的第一个键/值:

first_key = list(colors)[0]
first_val = list(colors.values())[0]

或者(避免将键视图实例化为列表):

def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError

first_key = get_first_key(colors)
first_val = colors[first_key]

如果您需要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已经包含有序字典,但这只是实现细节。语言规范包括3.7以后的有序字典。)

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

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

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.)


回答 2

处理字典中的元素就像坐在驴上,享受旅程。

作为Python的规则,字典是无序的

如果有

dic = {1: "a", 2: "aa", 3: "aaa"}

现在假设如果我喜欢dic[10] = "b",那么它不会总是这样添加

dic = {1:"a",2:"aa",3:"aaa",10:"b"}

可能像

dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}

要么

dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}

要么

dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}

或任何此类组合。

所以经验法则是字典无序的

Addressing an element of dictionary is like sitting on donkey and enjoy the ride.

As rule of Python DICTIONARY is orderless

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 = {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 DICTIONARY is orderless!


回答 3

如果需要有序字典,可以使用odict

If you need an ordered dictionary, you can use odict.


回答 4

实际上,我找到了一个新颖的解决方案,确实帮了我大忙,如果您特别关心列表或数据集中某个值的索引,则可以将dictionary的值设置为该Index !:

只是看:

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}

现在,借助哈希图的强大功能,您可以在恒定时间内(也就是快得多)拉入条目的索引

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)


回答 5

哦,那是一个艰难的过程。基本上,这里的每个项目都有两个值。然后,您尝试使用数字作为键来呼叫他们。不幸的是,您的值之一已经设置为键!

试试这个:

colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}

现在,您可以按数字调用键,就像它们像列表一样被索引。您还可以通过颜色和数字在列表中的位置进行引用。

例如,

colors[1][0]
// returns 'blue'

colors[3][1]
// returns '8'

当然,您将不得不想出另一种方式来跟踪每种颜色的位置。也许您可以拥有另一本字典来存储每种颜色的键值。

colors_key = {‘蓝色’:1,’红色’:6,’yllow’:8}

然后,您也可以根据需要查找颜色键。

colors [colors_key [‘blue’]] [0]将返回’blue’

这样的事情。

然后,当您使用它时,可以使用数字值作为键进行字典操作,以便始终可以使用它们来查找颜色(如果需要)。

值= {5:[1,’蓝色’],6:[2,’红色’],8:[3,’黄色’]}

然后,(colors [colors_key [values [5] [1]]] [0])将返回’blue’。

或者,您可以使用列表列表。

祝好运!

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}

Then, you will be able to also look up the colors key if you need to.

colors[colors_key[‘blue’]][0] will return ‘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’]}

Then, (colors[colors_key[values[5][1]]][0]) will return ‘blue’.

Or you could use a list of lists.

Good luck!


回答 6

您不能,因为它dict是无序的。您可以.popitem()用来获取任意项,但这会将其从dict中删除。

You can’t, since dict is unordered. you can use .popitem() to get an arbitrary item, but that will remove it from the dict.