【问题标题】:How to use default dict如何使用默认字典
【发布时间】:2022-12-09 12:48:39
【问题描述】:
iterator=0;
thisdict = {}
for country in countries.split(","):    
     try:
        thisdict.update({country: "1"})
     except Exception as e: 
      logging.info('Error occurred')

return thisdict

我想在 python 中使用接受重复键值对的数据结构。我了解到 defaultdict 是一个不错的选择。我怎样才能达到同样的效果。

更改 thisdict = defaultdict() 无效。

谢谢你。

【问题讨论】:

  • 你看过documentation了吗? defaultdict 的构造函数需要一个参数
  • dictdefaultdict 结构都不接受重复键。

标签: python dictionary key-value defaultdict


【解决方案1】:

defaultdict() 需要一个参数来指定一个为新元素创建默认值的函数。在这种情况下,您需要一个整数,因此使用defaultdict(int)

thisdict = defaultdict(int)

for country in countries.split(","):    
    thisdict[country] += 1

请注意,已经有一个内置的 collections.Counter() 将创建一个计数字典:

thisdict = collections.Counter(countries.split(","))

【讨论】:

  • 谢谢你。我希望它是一个字符串。我的结果应该是
猜你喜欢
  • 2011-06-29
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多