我是 python 初学者。我首先使用字典。
我有一个字典,它包含键的字母和值的任意值作为对,我想同时为每个键分配相同的值。我正在尝试按以下方式练习操作字典:
dict_ = {'a':1 , 'b': 2 , 'c': 3}
dict_ ['a'] = "It\'s an alphabet."
dict_ ['b'] = "It\'s an alphabet."
dict_ ['c'] = "It\'s an alphabet."
print dict_
假设我有很多键,要一个一个地设置键的每个值太麻烦了。 有什么好主意吗?
请您参考如下方法:
您可以使用 dict comprehension :
dict_ = {'a':1 , 'b': 2 , 'c': 3}
dict_ = {k:"It\'s an alphabet." for k in dict_}
然而,这会创建一个新字典。循环现有的是就地执行此操作的最佳解决方案:
for k in dict_:
dict_[k] = "It\'s an alphabet."
您可以使用 for k in mydict 遍历字典的所有键:
for k in mydict:
# this block of code will be executed once for each
# key in the dictionary. You can get the current key
# with `k`:
print k
上面的代码将打印字典的每个值。
因为您可以使用 mydict[mykey] = myvalue 分配给一个键,所以您在这里要做的就是为每个键分配“It\' s an alphabet" 在字典中。这是代码的作用:
# for each key `k` in the dictionary `dict_`
for k in dict_:
# assign "It\'s an alphabet" to it:
dict_[k] = "It\'s an alphabet"
