我想通过索引号遍历python中的字典。
例子 :
dict = {'apple':'red','mango':'green','orange':'orange'}
我想从头到尾遍历字典,以便可以通过索引访问字典项。例如,第一项是苹果,第二项是芒果,值是绿色。
像这样的东西:
for i in range(0,len(dict)):
dict.i
我想通过索引号遍历python中的字典。
例子 :
dict = {'apple':'red','mango':'green','orange':'orange'}
我想从头到尾遍历字典,以便可以通过索引访问字典项。例如,第一项是苹果,第二项是芒果,值是绿色。
像这样的东西:
for i in range(0,len(dict)):
dict.i
您可以遍历键并通过键获取值:
for key in dict.iterkeys():
print key, dict[key]
您可以迭代键和相应的值:
for key, value in dict.iteritems():
print key, value
如果你想要索引,你可以使用enumerate
(记住字典没有顺序):
>>> for index, key in enumerate(dict):
... print index, key
...
0 orange
1 mango
2 apple
>>>
这里有一些非常好的答案。我还想在此处添加以下内容:
some_dict = {
"foo": "bar",
"lorem": "ipsum"
}
for index, (key, value) in enumerate(some_dict.items()):
print(index, key, value)
结果是
0 foo bar
1 lorem ipsum
似乎与 Python2.7
和3.5
我今天想知道python OrderedDict 的(idx,key,value)(将 SKU 映射到数量,按照它们应该出现在收据上的顺序排列)。这里的答案都是无赖。
至少在 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
有些评论说这些答案与问题不对应是正确的。
人们可能想要使用“索引”遍历字典的一个原因是例如为字典中的一组对象计算距离矩阵。举个例子(稍微介绍一下下面项目符号的基础知识):
这就是为什么大多数包使用压缩距离矩阵(压缩距离矩阵如何工作?(pdist))
但是考虑一种情况是实现距离矩阵的计算,或者任何种类的排列。在这种情况下,您需要跳过一半以上案例的结果。这意味着遍历所有字典的 FOR 循环只是命中一个 IF 并跳转到下一个迭代,而大多数时间没有执行任何工作。对于大型数据集,这些额外的“IF”和循环会增加处理时间的相关数量,如果在每个循环中,在字典中进一步启动一个“索引”,则可以避免这种情况。
除了这个问题,我现在的结论是答案是否定的。除了键或迭代器之外,无法通过任何索引直接访问字典值。
我知道到目前为止,大多数答案都应用了不同的方法来执行此任务,但实际上不允许任何索引操作,这在示例的情况下会很有用。
我看到的唯一选择是使用列表或其他变量作为字典的顺序索引。这里有一个实现来举例说明这种情况:
#!/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
输出是:
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
还值得一提的是,诸如intertools 之类的包允许人们以更短的格式执行类似的任务。
做这个:
for i in dict.keys():
dict[i]
由于您想按顺序迭代,您可以使用sorted
:
for k, v in sorted(dict.items()):
print k,v
有几种方法可以在 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("-----------")
结果是:
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]
-----------
当我需要保持订单时,我使用一个列表和一个配套字典:
color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
color[i]
不便之处是我不容易从索引中得到结果。当我需要它时,我使用一个元组:
fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)):
fruitcolor[i][1]
for f, c in fruitcolor:
c
你的数据结构应该被设计成适合你的算法需求,这样它就可以保持干净、可读和优雅。
我想不出你为什么要这样做。如果你只需要遍历字典,你就可以做到。
for key, elem in testDict.items():
print key, elem
或者
for i in testDict:
print i, testDict[i]