Python 基于csv文件的字典更新
Python dictionary update based on csv file
我有一个 csv 文件,其中:
id, word, super_id
100 , cat, 5
5 , bird, Nan
3 , dog, 100
20, fox , 100
我创建了以下词典:d= {100: [5, 3, 20], 3: [100]}
- 其中节点 100 有父节点 5 和子节点 3、20
- 节点 3 有父节点 100,没有子节点
我需要更新字典,使其变成:
d= {cat: [bird, dog, fox], dog: [cat]}
或创建一个新的。
有什么想法吗?
你可以这样做
import csv
d = {100: [5, 3, 20], 3: [100]}
with open('file.csv', 'r') as csv_file:
rows = csv.reader(csv_file, skipinitialspace=True)
next(rows)
names = {int(row[0]): row[1] for row in rows}
result = {names[key]: [names[item_id] for item_id in value] for key, value in d.items()}
这是使用 csv
模块和几个字典理解的一种方法:
import csv
from io import StringIO
mystr = StringIO("""id, word, super_id
1 , cat, 2
2 , bird, Nan
3 , dog, 1
4, fox , 1""")
# replace mystr with open('file.csv', 'r')
with mystr as fin:
reader = csv.reader(fin, skipinitialspace=True)
next(reader) # ignore header row, or use headers = next(reader) to extract
fin_d = {int(ide): word for ide, word, super_id in reader}
d = {1: [2, 3, 4], 3: [1]}
# map keys and values of d using fin_d
res = {fin_d[k]: list(map(fin_d.get, v)) for k, v in d.items()}
print(res)
{'cat': ['bird', 'dog', 'fox '], 'dog': ['cat']}
我有一个 csv 文件,其中:
id, word, super_id
100 , cat, 5
5 , bird, Nan
3 , dog, 100
20, fox , 100
我创建了以下词典:d= {100: [5, 3, 20], 3: [100]}
- 其中节点 100 有父节点 5 和子节点 3、20
- 节点 3 有父节点 100,没有子节点
我需要更新字典,使其变成:
d= {cat: [bird, dog, fox], dog: [cat]}
或创建一个新的。
有什么想法吗?
你可以这样做
import csv
d = {100: [5, 3, 20], 3: [100]}
with open('file.csv', 'r') as csv_file:
rows = csv.reader(csv_file, skipinitialspace=True)
next(rows)
names = {int(row[0]): row[1] for row in rows}
result = {names[key]: [names[item_id] for item_id in value] for key, value in d.items()}
这是使用 csv
模块和几个字典理解的一种方法:
import csv
from io import StringIO
mystr = StringIO("""id, word, super_id
1 , cat, 2
2 , bird, Nan
3 , dog, 1
4, fox , 1""")
# replace mystr with open('file.csv', 'r')
with mystr as fin:
reader = csv.reader(fin, skipinitialspace=True)
next(reader) # ignore header row, or use headers = next(reader) to extract
fin_d = {int(ide): word for ide, word, super_id in reader}
d = {1: [2, 3, 4], 3: [1]}
# map keys and values of d using fin_d
res = {fin_d[k]: list(map(fin_d.get, v)) for k, v in d.items()}
print(res)
{'cat': ['bird', 'dog', 'fox '], 'dog': ['cat']}