【问题标题】:How to avoid overwriting result of dict comprehension when reading from CSV?从CSV读取时如何避免覆盖dict理解的结果?
【发布时间】:2020-01-31 21:33:26
【问题描述】:

考虑以下csv 文件:

Id,Country,Cities
1,Canada,"Toronto;Ottawa;Montreal"
2,Italy,"Rome;Milan;Naples;Palermo"
3,France,"Paris;Cannes;Lyon"
4,Spain,"Seville;Alicante;Barcelona"

我想读取字典中的城市名称和位置,键设置为“国家”,所以我这样做:

my_dict = {}
with open(DATA, 'r') as f:
  map_reader = csv.reader(f)
  field_names = next(map_reader)
  for row in map_reader:
     my_dict = { r:row[1] for r in row[2].split(";") }

print(my_dict)

这里的问题是,在每次迭代中,dict 推导的结果都会覆盖 my_dict。正确的使用方法是什么?

【问题讨论】:

  • 尝试使用my_dict.update({r:row[1] for r in row[2].split(";")})。这是向字典更新/添加键值对的方法。
  • @APhillips,非常感谢!这正是我错过的。

标签: python csv dictionary dictionary-comprehension


【解决方案1】:

你想更新现有的字典,而不是替换它。

for row in map_reader:
    my_dict.update({r: row[1] for r in row[2].split(";")})

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 2021-11-10
    • 2015-05-15
    • 1970-01-01
    • 2022-01-22
    • 2013-06-02
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多