Python 已加载带整数键的词典如何打印?
在Python 27中Python 已加载带整数键的词典如何打印?,python,dictionary,int,Python,Dictionary,Int,在Python 27中 p=100 dicthg = {} for i in range(10): print i dicthg = {i:p}; for i in range(10): print "-", i print dicthg[i] 关键错误 注释掉第二个for循环,它可以很好地打印dicthg[i] 在第二个for循环中尝试 for i in dicthg: 仅获取最后一项(索引9) 同一时间 for i,j in dicthg.items(
p=100
dicthg = {}
for i in range(10):
print i
dicthg = {i:p};
for i in range(10):
print "-", i
print dicthg[i]
关键错误
注释掉第二个for循环,它可以很好地打印dicthg[i]
在第二个for循环中尝试
for i in dicthg:
仅获取最后一项(索引9)
同一时间
for i,j in dicthg.items():
print i,j
我是Python新手,所以我为自己的无知提前道歉。我已经对以前的帖子进行了广泛的搜索。您没有加载它。在循环的每次迭代中,您都要替换整个字典。下面是加载它的方式
这是制作一本每次只有1个元素的新词典
for i in range(10):
print i
dicthg = {i:p}
现在,dicthg
具有以下值
{9: 100}
我猜你的意图如下
for i in range(10):
print i
dicthg[i] = p
现在看字典
{0: 100, 1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 100, 8: 100, 9: 100}
使用字典理解创建字典的另一种方法。要使代码正常工作,只需替换:
dicthg = {i:p}
为了
如果您想知道发生了什么,请在第一个循环中添加以下行:
print dicthg
这将显示第二个循环中出现
键错误的原因。以下是程序的修改版本:
p=100
dicthg = {}
for i in range(10):
print i
# This is correct/simple way of setting item in dictionary
dicthg[i] = p
print "value of i = " + str(i)
print "Setting i to 0 again"
i = 0
print "new value of i = " + str(i)
for i in range(10):
print "-", i
print dicthg[i]
所以我做了两个修改:
在字典中插入/添加项目
将i的值重置为0,这样我们可以从0迭代到10
希望这有帮助 在进入第二个循环之前,请尝试打印dicthg
。
dicthg.update({i:p})
print dicthg
p=100
dicthg = {}
for i in range(10):
print i
# This is correct/simple way of setting item in dictionary
dicthg[i] = p
print "value of i = " + str(i)
print "Setting i to 0 again"
i = 0
print "new value of i = " + str(i)
for i in range(10):
print "-", i
print dicthg[i]