【发布时间】:2016-03-31 19:00:37
【问题描述】:
在分配像'67.67.%s.%s' % (str(j), str(i))这样的python字符串格式返回值时,分配给dict的key和分配给dict的子dict中的key是不一致的。
例如:
i = 0
j = 1
dict_template = {"id": "1", "another_dict": {"value": "hello"}}
dict_list = []
for idx in list(range(2, 1002)):
new_dict = copy.copy(dict_template)
new_dict['id'] = 'obj_id_%s' % str(idx)
new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i))
dict_list.append(new_dict)
if i < 254:
i += 1
else:
j += 1
i = 1
在此示例中,每个 new_dict['another']['value'] 都是相同的字符串并具有相同的 id。
但是,如果我将这一行 new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i)) 更改为 new_dict["another_dict"] = '67.67.%s.%s' % (str(j), str(i)),每个 new_dict["another_dict"] 都会有不同的值。
顺便说一句,我使用的是 Python 3.4.3。
【问题讨论】:
标签: python string python-3.x dictionary