【问题标题】:How can you assign multiple inputs a single value in Python dictionaries? [duplicate]如何在 Python 字典中为多个输入分配单个值? [复制]
【发布时间】:2020-10-17 10:08:12
【问题描述】:

我想为国家/地区指定货币价值,但有些货币在多个国家/地区使用。我知道我可以为每个国家/地区单独分配它们,但是有更好的方法吗?我尝试过的是:

rates = { ('England', 'wales'): 'GBP' }

预期结果是:

rates['England'] = GBP
rates['wales'] = GBP

但这不起作用。我能做什么?

【问题讨论】:

  • rates = {'England': 'GBP', 'Wales': 'GBP'} 是正确的做法。

标签: python dictionary


【解决方案1】:

该用例没有任何语法糖,但您可以使用一些不太冗长的方法来获得相同的结果:

来自键

# first argument are all keys, second is default value (or None)
rates = dict.fromkeys(('England', 'wales'), 'GBP')

理解

rates = {k: 'GBP' for k in ('England', 'wales')}

【讨论】:

    【解决方案2】:

    你也许可以把这两个翻过来?

    rates = { 
    "GBP": ["England", "Wales"], 
    "EUR": ["Germany", "Fance", "Netherlands"] 
    }
    

    【讨论】:

      【解决方案3】:

      您可以创建国家列表并将它们全部添加到一个循环中:

      GBP_countries=['England', 'wales']
      rates = {}
      for country in  GBP_countries:
          rates.update({country:'GBP'})
      

      【讨论】:

      • 为什么将update 与单例dict 一起使用?只需绑定密钥即可。
      猜你喜欢
      • 1970-01-01
      • 2021-04-08
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多