Python 无法以字符串格式方法更新defaultdict

Python 无法以字符串格式方法更新defaultdict,python,format,defaultdict,Python,Format,Defaultdict,我试图为每个用户名生成随机颜色 当我编写代码时,name1和name2的颜色相同。这里怎么了 import random from collections import defaultdict def get_color(): print('call') return ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) colors = defaultdict(get_color) msg1 = {'

我试图为每个用户名生成随机颜色

当我编写代码时,name1和name2的颜色相同。这里怎么了

import random
from collections import defaultdict

def get_color():
    print('call')
    return ''.join([random.choice('0123456789ABCDEF') for j in range(6)])

colors = defaultdict(get_color)

msg1 = {'name' : 'name1'}
msg2 = {'name' : 'name2'}

for msg in [msg1, msg2]:
    msg = '{colors[name]} {name}'.format(colors=colors, **msg)
    print(msg)
输出:

召唤

72C44D名称1

72C44D名称2


谢谢您

您正在呼叫
get_colors()
仅一次,并将存储的颜色(在
colors
中)分配给这两条消息。按照以下步骤为每次迭代生成随机颜色:

for msg in [msg1, msg2]:
    msg = '{colors[name]} {name}'.format(colors=defaultdict(get_color), **msg)
    print(msg)

循环完成后打印
颜色将显示

defaultdict(<function get_color at 0x7f6e7faed1e0>, {'name': '67C80A'})
输出

{colors[name1]} {name}
call
A70B47 name1
{colors[name2]} {name}
call
55709A name2

我将生成内容与打印内容分开,以便于阅读。您可以简化您的代码,这将更容易

import random
from collections import defaultdict

def generate_color():
    color = ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
    print ('generate_color returns', color)
    return color

colors = defaultdict(generate_color)

# simplify this. It's just a list of names
names = ['name1', 'name2']

# to call generate_color once for each name, 
# all you need to do is access that name in the default dict
print ('building colors')
for name in names:
    colors[name]

# now you have populated colors.
print ('printing colors')
for key in colors:
    # I went with simplifying the format string
    print ('{} {}'.format(key, colors[key]))

我运行了代码。它为任何字符串生成相同的代码。
import random
from collections import defaultdict

def generate_color():
    color = ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
    print ('generate_color returns', color)
    return color

colors = defaultdict(generate_color)

# simplify this. It's just a list of names
names = ['name1', 'name2']

# to call generate_color once for each name, 
# all you need to do is access that name in the default dict
print ('building colors')
for name in names:
    colors[name]

# now you have populated colors.
print ('printing colors')
for key in colors:
    # I went with simplifying the format string
    print ('{} {}'.format(key, colors[key]))