可以创建这样的数据结构吗?
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)
有没有办法缩短它,然后轻松访问每个值的值?
您可以dict.fromkeys多次使用并合并结果:
w = dict(
**dict.fromkeys(['London', 'Glasgow', 'Dublin'], 'rainy'),
**dict.fromkeys(['Paris', 'Berlin'], 'cloudy'),
)
Run Code Online (Sandbox Code Playgroud)
有许多不同的方法来合并 dicts。**在创建时使用多个-operatorsdict只是其中之一。
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |