使用for循环的字典中的字典列表

Vig*_*raj 1 python dictionary for-loop python-2.7

我在python中为xlsxwriter创建一个随机颜色

import random
point = []
dict1 = {}
for row_count in range(3):

    fill = {
    "color": '#' + ''.join([random.choice('0123456789ABCDEF') for x in range(6)]),
}
    dict1['fill'] = fill
    print fill
    point.append(dict1)
print point
Run Code Online (Sandbox Code Playgroud)

预期产出

[{'fill': {'color': '#8C4372'}}, {'fill': {'color': '#5EF546'}}, {'fill': {'color': '#386CF4'}}]
Run Code Online (Sandbox Code Playgroud)

实际产出

{'color': '#8C4372'}
{'color': '#5EF546'}
{'color': '#386CF4'}
[{'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}]
Run Code Online (Sandbox Code Playgroud)

怎么解决这个问题.

提前致谢

小智 6

对所有填充对象使用相同的字典dict1,每次将其添加到点时创建新的填充对象:

import random
point = []
for row_count in range(3):
    fill = {
        "color": '#' + ''.join([random.choice('0123456789ABCDEF') for x in range(6)]),
    }
    point.append({"fill": fill})
Run Code Online (Sandbox Code Playgroud)


Joh*_*ter 6

问题是您正在重新使用dict1并重新分配"填充"键.由于它在所有条目之间共享,因此所有条目都将获得新值.改为:

import random

def random_color():
    return '#' + ''.join(random.choice('0123456789ABCDEF') for x in range(6))

rows = []
for _ in range(3):
    fill = {"color": random_color()}
    rows.append({"fill": fill})

print rows
Run Code Online (Sandbox Code Playgroud)

或者使用列表理解:

rows = [{'fill': {'color': random_color()}} for _ in range(3)]
Run Code Online (Sandbox Code Playgroud)