如何乘以字典键?

时间:2019-02-18 07:54:53

标签: python dictionary for-loop

我想将此字典的键乘以2

d = {2: (1,2), 8: (2,4), 30: (10,3)}

for i in d.keys():
    print(i*2)

4
16
60

但是d仍然是{2: (1,2), 8: (2,4), 30: (10,3)}

如何让d成为{4: (1,2), 16: (2,4), 60: (10,3)}

5 个答案:

答案 0 :(得分:0)

您可以尝试以下方法吗?

d = {2: (1,2), 8: (2,4), 30: (10,3)}
d = {k**2: v for k, v in d.items()}

答案 1 :(得分:0)

词典理解:

double = {k*2:v for (k,v) in d.items()}

答案 2 :(得分:0)

我相信你想要的是

将每个key2相乘。不是正方形。

d = {2: (1,2), 8: (2,4), 30: (10,3)}
d = {k*2: v for (k, v) in d.items()}
print(d)

输出:

{4: (1, 2), 16: (2, 4), 60: (10, 3)}

答案 3 :(得分:0)

new_d = {}
for k,v in d.items():
    new_d[k*2] = v
d = new_d

答案 4 :(得分:0)

尝试一下:

d = dict((key*2, value) for (key, value) in d.items())