【发布时间】:2017-01-03 14:11:15
【问题描述】:
我是 Python 的新手,并试图“在工作中”学习它。我必须这样做。
是否可以动态创建一个“dictionary1”,它以另一个“dictionary2”为值,其中“dictionary2”也在每个 for 循环中更新。基本上就代码而言,我尝试过:
fetch_value = range(5) #random list of values (not in sequence)
result = {} #dictionary2
ret = {} #dictionary1
list1 = [0, 1] #this list is actually variable length, ranging from 1 to 10 (assumed len(list1) = 2 for example purpose only)
for idx in list1:
result[str(idx)] = float(fetch_value[1])
ret['key1'] = (result if len(list1) > 1 else float(fetch_value[1])) # key names like 'key1' are just for representations, actual names vary
result[str(idx)] = float(fetch_value[2])
ret['key2'] = (result if len(list1) > 1 else float(fetch_value[2]))
result[str(idx)] = float(fetch_value[3])
ret['key3'] = (result if len(list1) > 1 else float(fetch_value[3]))
result[str(idx)] = float(fetch_value[4])
ret['key4'] = (result if len(list1) > 1 else float(fetch_value[4]))
print ret
这输出到:
{'key1': {'0': 4, '1', 4}, 'key2': {'0': 4, '1', 4}, 'key3': {'0': 4, '1', 4}, 'key4': {'0': 4, '1', 4}}
我需要什么:
{'key1': {'0': 1, '1', 1}, 'key2': {'0': 2, '1', 2}, 'key3': {'0': 3, '1', 3}, 'key4': {'0': 4, '1', 4}}
有什么明显的我做错了吗?
【问题讨论】:
-
您需要通过
result.copy()使用内部字典的副本 -
您可能希望使用字典理解来根据需要创建新的内部字典,而不是重复复制一个字典,例如
{key: {idx: fetch_value(idx) for idx in [0, 1]} for key in range(1, 5)}. -
@MosesKoledoye 谢谢!这很有用,但现在通过将上面代码中的 result 替换为 result.copy(),输出为
{'key1': {'0': 4, '1', 1}, 'key2': {'0': 4, '1', 2}, 'key3': {'0': 4, '1', 3}, 'key4': {'0': 4, '1', 4}} -
所以你正在做一些奇怪的事情。您的 (result if len(list1) > 1 else float(fetch_value[1])) 将始终评估为 true 对吗? len(list1) 不会改变
-
也许你想用 for i,idx in enumerate(list1)
标签: python for-loop dictionary nested dictionary-comprehension