如何用CSV共享密钥编写两个python词典?

时间:2017-10-01 05:46:11

标签: python

我有以下两个词典: dict1 = {' a':100,'':200,' c':300} dict2 = {' a':0.20,' b':0.25,' c':0.30}

我想把它写成CSV格式:

Key Value1 Value2
一个100 0.20
b 200 0.25
c 300 0.30

2 个答案:

答案 0 :(得分:1)

具有相同键集的词典

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30}

with open('some_file','w') as f:
    f.write('Key\tValue1\tValue2\n')
    for k in sorted(dict1.keys()):
        f.write("{0}\t{1}\t{2}\n".format(k,dict1[k],dict2[k]))

迭代一个键集,并从两个字典中打印出值。 (Bonus:适用于Python 2和Python 3。)

具有不相交键集的字典

对于那些希望找到可能存在多个词典的问题的答案的人,以及可能不相交的键集,这里有一个(有点hacky)答案:

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30,'d':0.40}
dict3 = {'a':2000,'b':2500,'d':9000,'e':9500}

with open('some_file','w') as f:
    f.write('Key\tValue1\tValue2\tValue3\n')
    keys_union = set(dict1.keys()).union(set(dict2.keys())).union(set(dict3.keys()))
    for k in sorted(keys_union):
        f.write("{0}\t{1}\t{2}\t{3}\n".format( k,
                        [dict1[k] if k in dict1.keys() else "-"][0],
                        [dict2[k] if k in dict2.keys() else "-"][0],
                        [dict3[k] if k in dict3.keys() else "-"][0]))

这会为其中一个词典中缺少的值打印“ - ”。

答案 1 :(得分:1)

您可以将字典写入pandas data-frame,即 ```

from tabulate import tabulate
import pandas as pd

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30}

df = pd.Series(dict1,name='Value 1').to_frame()
df['Value 2'] = dict2.values()
print(tabulate(df, headers= 'keys', tablefmt= 'grid'))

打印df生成

+----+-----------+-----------+
|    |   Value 1 |   Value 2 |
+====+===========+===========+
| a  |       100 |      0.2  |
+----+-----------+-----------+
| b  |       200 |      0.25 |
+----+-----------+-----------+
| c  |       300 |      0.3  |
+----+-----------+-----------+

pandas系列是一维数据结构,它将字典dict1转换为一个系列,其中字典键作为索引,字典值作为系列值。 to_frame将系列转换为包含一列的数据框(2D数据结构或表),第df['Value 2'] = dict2.values()行将dict2添加为数据框df中的第二列。<登记/> 您可以使用

将结果数据帧写入csv文件
df.to_csv('filename here')

这是使用cat转储文件内容的结果 image of the result of dumping the file content to screen

PS。制表只需将数据框转换为装饰文本以进行打印

编辑: 这太过分了; 为了获得准确的输出,可以重置/重命名索引,然后将to_csv参数index设置为False;意味着不存储索引 enter image description here