从excel数据循环到每个键有多个值的字典
我相当新的Python,我认为这个问题是相当容易,但我不明白…
我在Excel中有一个数据表,我有B列string和C到I列作为值。 我想创build一个字典,其中为B列中的每个键值,我分配C到列的值我想出了如何做到每行,一次在一次,但我正在寻找for
循环语法在整个excel数据表中做到这一点。
这是我的代码:
NYSE = {} NYSE.setdefault(sheet['B5'].value, []).append(sheet['C5'].value) NYSE.setdefault(sheet['B5'].value, []).append(sheet['D5'].value) NYSE.setdefault(sheet['B6'].value, []).append(sheet['C6'].value) NYSE.setdefault(sheet['B6'].value, []).append(sheet['D6'].value) print NYSE
我可以保持手动添加到此… B7 C7,B7 D7等,但必须有一种方法来循环此function,并输出字典。
你可以尝试这样的事情:
from collections import defaultdict d = defaultdict(list) for line in open("pyex.csv").readlines(): line = line.strip() line = line.split(",") key, value = line[0], line[1:] d[key] += value print(d)
所以如果你有一个像这样的csv文件。 第一列是string,第二列和第二列是值:
crow 19 13 bird 16 32
这段代码会输出:
defaultdict(<class 'list'>, {'crow ': ['19', '13'], 'bird': ['16', '32']})
[0.1s完成]
这允许您为每个键具有多个值,因为值包含在列表中。
更新:
改用setdefault
:
d = {} for line in open("pyex.csv").readlines(): line = line.strip() line = line.split(",") key = line[0] for value in line[1:]: d.setdefault(key, []).append(value) print(d)
输出:
{'crow': ['19', '13'], 'bird': ['16', '32']}
甚至与csv库
import csv csv_file = open("pyex.csv") csv_reader = csv.reader(csv_file) d = {} for line in csv_reader: key = line[0] for value in line[1:]: d.setdefault(key, []).append(value) print(d)
正如@martineu所说,你不需要defaultdicts或setdefaults:
import csv csv_file = open("Book1.csv") csv_reader = csv.reader(csv_file) d = {} for line in csv_reader: key = line[0] d[key] = line[1:] print(d)
你有没有考虑过使用pandas? 我不确定你的目标是什么数据,但它似乎是最强大的方式来做你想做的。
如果使用pandas.read_excel(path, sheetname=None)
那么它将默认创build一个字典,其中每个键是一个表,每个值是该表的一个数据框。 然后你可以迭代你的字典来合并它们。 用数据的伪样本来获得更具体的信息会更容易一些。