You can use dict.update
to merge the contents of one dict into another. I'd also use defaultdict
to manage the dict of dicts, since then you can just merge data in without having to check whether the dict needs to be created first.
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)
Note that if you have variables like filename1
and filename2
and copy+pasted code that does roughly the same thing to both/all of them, it's usually a good clue that you should be using a list and a for
loop instead! :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…