Python 按索引迭代字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17793364/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:13:25  来源:igfitidea点击:

Python Iterate Dictionary by Index

pythondictionary

提问by Dev.K.

I want to iterate through a dictionary in python by index number.

我想通过索引号遍历 python 中的字典。

Example :

例子 :

 dict = {'apple':'red','mango':'green','orange':'orange'}

I want to iterate through the dictionary from first to last, so that I can access the dictionary items by their indexes. For example, the 1st item will be apple, and the 2nd item will be mango and value will be green.

我想从头到尾遍历字典,以便我可以通过索引访问字典项。例如,第一项是苹果,第二项是芒果,值是绿色。

Something like this:

像这样的东西:

for i in range(0,len(dict)):
    dict.i

采纳答案by Sukrit Kalra

I can't think of any reason why you would want to do that. If you just need to iterate over the dictionary, you can just do.

我想不出你为什么要这样做的任何理由。如果你只需要遍历字典,你可以这样做。

for key, elem in testDict.items():
    print key, elem

OR

或者

for i in testDict:
     print i, testDict[i]

回答by Mark Nenadov

Do this:

做这个:

for i in dict.keys():
  dict[i]

回答by alecxe

You can iterate over keys and get values by keys:

您可以遍历键并通过键获取值:

for key in dict.iterkeys():
    print key, dict[key]

You can iterate over keys and corresponding values:

您可以迭代键和相应的值:

for key, value in dict.iteritems():
    print key, value

You can use enumerateif you want indexes (remember that dictionaries don't have an order):

enumerate如果需要索引,可以使用(请记住,字典没有顺序):

>>> for index, key in enumerate(dict):
...     print index, key
... 
0 orange
1 mango
2 apple
>>> 

回答by jh314

Since you want to iterate in order, you can use sorted:

由于您想按顺序迭代,您可以使用sorted

for k, v in sorted(dict.items()):
    print k,v

回答by untitled90

I wanted to know (idx, key, value) for a python OrderedDict today (mapping of SKUs to quantities in order of the way they should appear on a receipt). The answers here were all bummers.

我今天想知道 Python OrderedDict 的 (idx, key, value)(将 SKU 映射到数量,按照它们在收据上出现的顺序)。这里的答案都是无赖。

In python 3, at least, this way works and and makes sense.

至少在python 3中,这种方式有效并且有意义。

In [1]: from collections import OrderedDict
   ...: od = OrderedDict()
   ...: od['a']='spam'
   ...: od['b']='ham'
   ...: od['c']='eggs'
   ...: 
   ...: for i,(k,v) in enumerate(od.items()):
   ...:    print('%d,%s,%s'%(i,k,v))
   ...: 
0,a,spam
1,b,ham
2,c,eggs

回答by Serguei Fedorov

There are some very good answers here. I'd like to add the following here as well:

这里有一些非常好的答案。我还想在这里添加以下内容:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

结果是

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7and 3.5

似乎适用于 Python2.73.5

回答by Dr Neo

There are several ways to call the for-loop in python and here what I found so far:

有几种方法可以在 python 中调用 for 循环,这是我目前发现的:

A = [1,2,3,4]
B = {"col1": [1,2,3],"col2":[4,5,6]}

# Forms of for loop in python:
# Forms with a list-form,
for item in A:
    print(item)
print("-----------")
  for item in B.keys():
    print(item)
print("-----------")
  for item in B.values():
    print(item)
print("-----------")
  for item in B.items():
    print(item)
    print("The value of keys is {} and the value of list of a key is {}".format(item[0],item[1]))
print("-----------")

Results are:

结果是:

1
2
3
4
-----------
col1
col2
-----------
[1, 2, 3]
[4, 5, 6]
-----------
('col1', [1, 2, 3])
The value of keys is col1 and the value of list of a key is [1, 2, 3]
('col2', [4, 5, 6])
The value of keys is col2 and the value of list of a key is [4, 5, 6]
-----------

回答by Fábio Lob?o

Some of the comments are right in saying that these answers do not correspond to the question.

有些评论说这些答案与问题不符是正确的。

One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):

人们可能想要使用“索引”遍历字典的一个原因是例如计算字典中一组对象的距离矩阵。举个例子(稍微介绍一下下面项目符号的基础知识):

  • Assuming one have 1000 objects on a dictionary, the distance square matrix consider all combinations from one object to any other and so it would have dimensions of 1000x1000 elements. But if the distance from object 1 to object 2 is the same as from object 2 to object 1, one need to compute the distance only to less than half of the square matrix, since the diagonal will have distance 0 and the values are mirrored above and below the diagonal.
  • 假设一个字典中有 1000 个对象,距离方阵考虑从一个对象到任何其他对象的所有组合,因此它的维度为 1000x1000 元素。但是,如果从对象 1 到对象 2 的距离与从对象 2 到对象 1 的距离相同,则只需计算不到方阵一半的距离,因为对角线的距离为 0 并且值在上方镜像和对角线下方。

This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist))

这就是为什么大多数包使用压缩距离矩阵的原因(压缩距离矩阵如何工作?(pdist)

But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.

但请考虑一种情况,即实现距离矩阵的计算,或任何类型的排列。在这种情况下,您需要跳过一半以上案例的结果。这意味着遍历所有字典的 FOR 循环只是命中 IF 并跳转到下一次迭代,而大部分时间都没有真正执行任何工作。对于大型数据集,这种额外的“IF”和循环加起来相当于处理时间的相关量,如果在每个循环中,在字典上进一步启动一个“索引”,则可以避免。

Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.

除了这个问题,我现在的结论是答案是否定的。除了键或迭代器之外,无法通过任何索引直接访问字典值。

I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.

我知道到目前为止,大多数答案都采用不同的方法来执行此任务,但实际上不允许进行任何索引操作,这在诸如示例之类的情况下会很有用。

The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:

我看到的唯一替代方法是使用列表或其他变量作为字典的顺序索引。这里有一个实现来举例说明这种情况:

#!/usr/bin/python3

dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))

key_list = list(dishes.keys())
number_of_items = len(key_list)

condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0

for first_index in range(0,number_of_items):
    for second_index in range(first_index+1,number_of_items):
        condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
        print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
        c_m_index+=1

The output is:

输出是:

Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}

0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25

Its also worth mentioning that are packages such as intertoolsthat allows one to perform similar tasks in a shorter format.

还值得一提的是,诸如intertools 之类的软件包可以让人们以更短的格式执行类似的任务。