Python 如何使用元组迭代字典?
因此,我需要迭代python中的字典,其中键是元组,值是整数。 我只需要打印出键和值。 我试过这个:Python 如何使用元组迭代字典?,python,dictionary,tuples,iteration,Python,Dictionary,Tuples,Iteration,因此,我需要迭代python中的字典,其中键是元组,值是整数。 我只需要打印出键和值。 我试过这个: 对于键,dict中的值: 但不起作用,因为它将元组的第一个元素分配给键和值,第二个元素分配给值 那我该怎么做呢?试试以下方法: for item in a_dict.items(): print(item) 您将看到它打印一个元组,该元组是键和值,项[0]应该是您的touble,项[1]应该是存储在该键下的值。您认为对于键,dict中的值同时迭代键和值的假设是错误的。 你需要做什么 fo
对于键,dict中的值:
但不起作用,因为它将元组的第一个元素分配给键和值,第二个元素分配给值
那我该怎么做呢?试试以下方法:
for item in a_dict.items():
print(item)
您将看到它打印一个元组,该元组是键和值,项[0]应该是您的touble,项[1]应该是存储在该键下的值。您认为
对于键,dict
中的值同时迭代键和值的假设是错误的。
你需要做什么
for key in dict:
print("key: " + key)
print("value: " + dict[key])
或者,如果你喜欢:
for key,value in dict.items():
print("key: " + key)
print("value: " + value)
如果元组中需要两个键,也可以这样做
for (key1, key2),value in dict.items():
print("key1: " + key1)
print("key2: " + key2)
print("value: " + value)
只用
用于输入指令
然后使用dict[key]pls访问该值。显示一些数据。
# regarding a proposed edit:
# dict() can be used to initialize a dict from different formats
# it accepts for instance a dict or a list of tuples
# in case of a static dict like below, only using {..} is sufficient
dot = dict({
('a', 'b'): 1,
('c', 'd'): 2
})
for k, v in dot.items():
print(k, " and ", v)