使用元组将值添加到字典键
using tuples to add values to dictionary keys
代码是我写的
population = {
'Shanghai': 17.8,
'Istanbul': 13.3,
'Karachi': 13.0,
'Mumbai': 12.5
}
bob, chase, exacu = 32, 42, 53
ha = bob, chase, exacu
population['bob', 'chase', 'exacu'] = ha
print(population)
我收到了输出
{'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, ('bob', 'chase', 'exacu'): (32, 42, 53)}
我期待输出
{'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, 'bob': 32, 'chase': 42, 'exacu': 53}
谁能解释一下如何收到预期的输出?谢谢!
你不能像这样分配给多个键,那只会使一个键由元组组成。
population = {
'Shanghai': 17.8,
'Istanbul': 13.3,
'Karachi': 13.0,
'Mumbai': 12.5
}
bob, chase, exacu = 32, 42, 53
ha = bob, chase, exacu
keys = 'bob', 'chase', 'exacu'
for x,y in zip(keys,ha):
population[x] = y
print(population)
>>> {'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, 'bob': 32, 'chase': 42, 'exacu': 53}
代码是我写的
population = {
'Shanghai': 17.8,
'Istanbul': 13.3,
'Karachi': 13.0,
'Mumbai': 12.5
}
bob, chase, exacu = 32, 42, 53
ha = bob, chase, exacu
population['bob', 'chase', 'exacu'] = ha
print(population)
我收到了输出
{'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, ('bob', 'chase', 'exacu'): (32, 42, 53)}
我期待输出
{'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, 'bob': 32, 'chase': 42, 'exacu': 53}
谁能解释一下如何收到预期的输出?谢谢!
你不能像这样分配给多个键,那只会使一个键由元组组成。
population = {
'Shanghai': 17.8,
'Istanbul': 13.3,
'Karachi': 13.0,
'Mumbai': 12.5
}
bob, chase, exacu = 32, 42, 53
ha = bob, chase, exacu
keys = 'bob', 'chase', 'exacu'
for x,y in zip(keys,ha):
population[x] = y
print(population)
>>> {'Shanghai': 17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5, 'bob': 32, 'chase': 42, 'exacu': 53}