[英]Create a dynamic nested dictionary in python using for loop
I am new to Python, and trying to learn it "on the job". 我是Python新手,并试图“在工作中”学习它。 And I am required to do this. 我需要这样做。
Is it possible to create a 'dictionary1' dynamically which takes another 'dictionary2' as value, where 'dictionary2' is also getting updated in every for loop. 是否可以动态创建'dictionary1',将另一个'dictionary2'作为值,其中'dictionary2'也在每个for循环中得到更新。 Basically in terms of code, I tried: 基本上在代码方面,我试过:
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
This outputs to: 这输出到:
{'key1': {'0': 4, '1', 4}, 'key2': {'0': 4, '1', 4}, 'key3': {'0': 4, '1', 4}, 'key4': {'0': 4, '1', 4}}
What I need: 我需要的:
{'key1': {'0': 1, '1', 1}, 'key2': {'0': 2, '1', 2}, 'key3': {'0': 3, '1', 3}, 'key4': {'0': 4, '1', 4}}
anything obvious I am doing wrong here? 什么明显的我在这里做错了?
There are two problems: 有两个问题:
ret
to it. 当您将一个键设置为ret
时,您需要创建结果字典的副本。 Otherwise, it will always hold a reference back to the same dictionary. 否则,它将始终保持对同一字典的引用。 ret
dictionary (containing {'0': 4}
) at the beginning of your second loop, and that would get copied to all of the keys. 通过该更改,您将在第二个循环的开头ret
最后一个ret
字典(包含{'0': 4}
),并将其复制到所有键。 A more concise way to do this would be a dictionary comprehension: 更简洁的方法是字典理解:
fetch_value = range(5)
list1 = [0, 1]
print {
'key{}'.format(i): {
str(list_item): float(fetch_value[i]) for list_item in list1
} if len(list1) > 1 else float(fetch_value[i])
for i in xrange(1, 5)
}
Output: 输出:
{
'key3': {'1': 3.0, '0': 3.0},
'key2': {'1': 2.0, '0': 2.0},
'key1': {'1': 1.0, '0': 1.0},
'key4': {'1': 4.0, '0': 4.0}
}
And with list1 = [0]
, where it seems you want a float value instead of a dictionary, the output would be: 并且使用list1 = [0]
,您似乎需要浮点值而不是字典,输出将是:
{'key3': 3.0, 'key2': 2.0, 'key1': 1.0, 'key4': 4.0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.