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

时间:2018-10-24 12:48:19

标签: 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 = {'name' : 'name1'}
msg2 = {'name' : 'name2'}

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

输出:

  

致电

     

72C44D名称1

     

72C44D名称2

谢谢

3 个答案:

答案 0 :(得分:3)

在循环完成后打印colors会显示

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

color只有一个密钥。您正在通过硬编码密钥colors['name']访问'name',而不是通过动态名称访问colors[name]

您还需要一个格式化步骤。一个用于构建模板,另一个用于将colors[name]插入模板。

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_template = '{{colors[{name}]}} {{name}}'.format(**msg)
    print(msg_template) # for demo purposes
    msg = msg_template.format(colors=colors, **msg)
    print(msg)

输出

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

答案 1 :(得分:0)

您仅呼叫get_colors()一次,并且将存储的颜色(在colors中分配给这两个消息。像下面这样为每次迭代生成随机颜色:

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

答案 2 :(得分:0)

我将生成物与印刷品分开,以使其更易于阅读。您可以简化代码,这将变得更加容易。

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