python - 使用for循环在python中创建动态嵌套字典

标签 python for-loop dictionary nested dictionary-comprehension

我是 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}}

有什么明显的我做错了吗?

最佳答案

有两个问题:

  1. 当您在 ret 中设置一个键时,您需要创建结果字典的副本。否则,它将始终保留对同一词典的引用。
  2. 通过该更改,您将在第二个循环的开头保留最后一个 ret 字典(包含 {'0': 4}),这将复制到所有键。

一个更简洁的方法是字典理解:

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)
}

输出:

{
    '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}
}

对于 list1 = [0],您似乎想要一个浮点值而不是字典,输出将是:

{'key3': 3.0, 'key2': 2.0, 'key1': 1.0, 'key4': 4.0}

关于python - 使用for循环在python中创建动态嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174170/

相关文章:

python - 保存前 django 模型与两个模型的关系

python - 我的 python 代码有什么问题? (乘法程序)

javascript - JavaScript中for循环访问数组时 'i'的作用是什么?

loops - for循环中的Python循环计数器

android - 字典应用程序中的发音?

python - 如何自定义python DataFrame散点图颜色?

python - 如何在 Seaborn 的 Pairplot 中绘制右轴和上轴并删除左轴和下轴?

java - 努力用 Java 制作 HTML 编辑器

python - 在Python字典中for循环时添加相同的键和值

c++ - 错误 : expected ‘,’ or ‘...’ before ‘>’ token