python可以一次为不同的键分配相同的值吗?

seb*_*elk 2 python dictionary

可以创建这样的数据结构吗?

w = {'London', 'Glasgow', 'Dublin' : 'rainy' , 'Paris', 'Berlin':  'cloudy', 'Tokyo', 'Montevideo' : 'sunny' }
Run Code Online (Sandbox Code Playgroud)

(当然上面有无效的语法)

我想避免写:

w = {'London' : 'rainy' , 'Glasgow' : 'rainy', 'Dublin' : 'rainy' , 'Paris' : 'cloudy' , 'Berlin':  'cloudy', 'Tokyo' : 'sunny' , 'Montevideo' : 'sunny' }
Run Code Online (Sandbox Code Playgroud)

有没有办法缩短它,然后轻松访问每个值的值?

shx*_*hx2 5

您可以dict.fromkeys多次使用并合并结果:

w = dict(
    **dict.fromkeys(['London', 'Glasgow', 'Dublin'], 'rainy'),
    **dict.fromkeys(['Paris', 'Berlin'], 'cloudy'),
)
Run Code Online (Sandbox Code Playgroud)

许多不同的方法来合并 dicts**在创建时使用多个-operatorsdict只是其中之一。