如何索引成字典?

时间:2022-02-13 04:18:33

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]颜色将返回一个键错误。

7 个解决方案

#1


68  

Dictionaries are unordered in Python. 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, respectively. So if you need them more then once, store the list in a variable to improve performance.)

在Python中字典是无序的。如果您不关心条目的顺序,并且希望通过索引访问键或值,那么可以使用d.keys()[i]和d.values()[i]或d.items()[i]。(注意,这些方法分别创建了所有键、值或项的列表。因此,如果您需要它们,那么请将列表存储在一个变量中,以提高性能。

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

如果不需要按键访问。(顺便问一下,你的数字为什么是字符串?)

#2


32  

If anybody still looking at this question, the currently accepted answer is now outdated:

如果有人还在看这个问题,目前公认的答案已经过时了:

Since Python 3.6 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.6的字典是保存和保存的,所以它们现在的行为完全是集合。OrderedDicts。不幸的是,仍然没有专门的方法来索引字典的键()/值(),所以在字典中获取第一个键/值可以这样做

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

or alternatively (this avoids instantiating the keys view into a list):

或者(这样可以避免将keys视图实例化为列表):

def get_first_key(dictionary):
    for key in dictionary.keys():
        return key

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

If you need an n-th key, then similarly

如果你需要第n个键,那么类似地

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

#3


3  

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

如果你需要一个有序的字典,你可以使用odict来。

#4


3  

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

编字典就像坐在驴子上享受旅途一样。

As rule of Python DICTIONARY is orderless

因为Python字典的规则是无序的

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

所以拇指规则是字典是无序的!

#5


3  

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!:

事实上,我找到了一个新颖的解决方案,这对我很有帮助。如果你特别关注列表或数据集中某个值的索引,你可以将dictionary的值设置为该索引!

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)

现在通过hashmaps的强大功能,您可以在常数时间内拉出索引(也就是更快)

#6


1  

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

你不能,因为字典是无序的。可以使用.popitem()获取任意项,但这会将其从dict语句中删除。

#7


0  

Dictionaries are not lists.

字典不是列表。

with lists you can just do enter foo[0] here to get that value.

对于列表,你可以在这里输入foo[0]来获得那个值。

dicts got .value and .keys() functions.

dicts有。value和。keys()函数。

Its also more adviceable to use try/except anytime you iterate through a dict.

使用try/除了在遍历一条法令时使用它也更可取。

#1


68  

Dictionaries are unordered in Python. 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, respectively. So if you need them more then once, store the list in a variable to improve performance.)

在Python中字典是无序的。如果您不关心条目的顺序,并且希望通过索引访问键或值,那么可以使用d.keys()[i]和d.values()[i]或d.items()[i]。(注意,这些方法分别创建了所有键、值或项的列表。因此,如果您需要它们,那么请将列表存储在一个变量中,以提高性能。

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

如果不需要按键访问。(顺便问一下,你的数字为什么是字符串?)

#2


32  

If anybody still looking at this question, the currently accepted answer is now outdated:

如果有人还在看这个问题,目前公认的答案已经过时了:

Since Python 3.6 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.6的字典是保存和保存的,所以它们现在的行为完全是集合。OrderedDicts。不幸的是,仍然没有专门的方法来索引字典的键()/值(),所以在字典中获取第一个键/值可以这样做

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

or alternatively (this avoids instantiating the keys view into a list):

或者(这样可以避免将keys视图实例化为列表):

def get_first_key(dictionary):
    for key in dictionary.keys():
        return key

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

If you need an n-th key, then similarly

如果你需要第n个键,那么类似地

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

#3


3  

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

如果你需要一个有序的字典,你可以使用odict来。

#4


3  

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

编字典就像坐在驴子上享受旅途一样。

As rule of Python DICTIONARY is orderless

因为Python字典的规则是无序的

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

所以拇指规则是字典是无序的!

#5


3  

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!:

事实上,我找到了一个新颖的解决方案,这对我很有帮助。如果你特别关注列表或数据集中某个值的索引,你可以将dictionary的值设置为该索引!

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)

现在通过hashmaps的强大功能,您可以在常数时间内拉出索引(也就是更快)

#6


1  

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

你不能,因为字典是无序的。可以使用.popitem()获取任意项,但这会将其从dict语句中删除。

#7


0  

Dictionaries are not lists.

字典不是列表。

with lists you can just do enter foo[0] here to get that value.

对于列表,你可以在这里输入foo[0]来获得那个值。

dicts got .value and .keys() functions.

dicts有。value和。keys()函数。

Its also more adviceable to use try/except anytime you iterate through a dict.

使用try/除了在遍历一条法令时使用它也更可取。