我的最小工作示例如下:我有一个循环迭代一定次数。在每次迭代中,我都想创建一个新的关键字,其名称取决于当前的索引值,例如key_j,并为其分配一个特定的值。有没有办法做到这一点?
for j in range(10):
dict[key_j] = j**2
谢谢
最佳答案
您可以使用字符串格式来创建具有当前循环索引的字符串键
res = {}
for j in xrange(10):
key_j = 'key_{}'.format(j) # a string depending on j
res[key_j] = j**2
生成的
res
字典为:{'key_5': 25, 'key_4': 16, 'key_7': 49, 'key_6': 36,
'key_1': 1, 'key_0': 0, 'key_3': 9, 'key_2': 4, 'key_9': 81,
'key_8': 64}
请注意,字典键的顺序是,而不是。如果要保留顺序,则需要使用
OrderedDict
而不是常规dict
。顺便提一句,
字典键不必是字符串,您也可以将
int
用作键(实际上每个"hashable"对象都可以用作键):res = {}
for j in xrange(10):
res[j] = j**2 # int as key
结果是:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
在此示例中, key 是有序的,但是并非保证如此。
请注意,您可以使用dictionary comprehension创建
res
字典,例如:res = {j: j**2 for j in xrange(10)}
或者
res = {'key_{}'.format(j): j**2 for j in xrange(10)}
关于Python:字典键名可在循环中动态更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44881327/