遍历键并添加缺失值

loop over keys and add missing values

我正在将 csv 文件转换为字典,这两个 csv 文件相似但具有不同的值。所以一个 csv 文件有 {name, state, website} 而另一个有 {name, state, car}。这些文件中有一些相同的人,所以我想遍历键,如果它们具有相同的名称,则添加缺少的键,例如,如果两者都有一个名为 John Williams 的人,它会找到该名称并创建一个新字典说 {name: 'John Williams', state: 'FL', website "https://helpmeplease.com", car: "Kia"}。如果有一个新人,那么我希望它创建一个新的行并将其添加到字典中。

我已将 csv 文件转换为字典,目前正在比较密钥 'names',但我被困在这里,不知道从这里去哪里。

import csv
filename1 ="example.csv"
filename2 = "example2.csv"

blue = {}

with open(filename1, 'r', newline='') as f:
 for line in csv.DictReader(f):
    blue[line['name']] = line

with open(filename2, 'r', newline='') as h:
 for line in csv.DictReader(h):
    if line['name'] in blue.keys():
      #This is where I'm stuck
    else:
        blue[line['name']] = line

您可以使用 dict.update 将一个字典的内容合并到另一个字典中。我还会使用 defaultdict 来管理字典中的字典,这样你就可以直接合并数据,而不必先检查是否需要创建字典。

import csv
from collections import defaultdict

filenames = ["example.csv", "example2.csv"]

fire = defaultdict(dict)  # type: Dict[str, Dict[str, str]]

for filename in filenames:
    with open(filename, 'r', newline='') as f:
        for row in csv.DictReader(f):
            fire[row['name']].update(row)

请注意,如果您有 filename1filename2 之类的变量,并且复制粘贴的代码对其中的 both/all 执行大致相同的操作,这通常是一个很好的线索,您可以应该改用列表和 for 循环! :)