简体   繁体   English

Python:在.csv文件中打印嵌套字典,如何删除[]和'

[英]Python: Printing nested dictionary in .csv file, how to remove [] and '

Say I have a dictionary: 假设我有一本字典:

d = {'Bob': {'Car': ['a = 1.10', 'b = 1.50'], 'House': ['c = 1.20'], 'Hp': 'true', 'Wife': 'false'},
     'Sam': {'Car': ['d = 1.40'], 'House': ['c = 1.60'], 'Hp': 'true', 'Wife': 'true'}}

I want to print it in a table in .csv file. 我想将其打印在.csv文件的表中。

My desired output (when opened in Excel): 我想要的输出(在Excel中打开时):

Name Hp    Wife  Car                 House
Bob  true  false a = 1.10, b = 1.50  c = 1.20
Sam  true  true  d = 1.60            c = 1.40

My code so far: 到目前为止,我的代码:

header = ['Name', 'Hp', 'Wife', 'Car', 'House']
with open("output.csv", "w") as f:
    w = csv.DictWriter(f, header)
    w.writeheader()
    for key, val in sorted(d.items()):
        row = {'Name': key}
        row.update(val)
        w.writerow(row)

But the output that I got is this (when opened in Excel): 但是我得到的输出是这样的(在Excel中打开时):

Name Hp    Wife  Car                         House
Bob  true  false "['a = 1.10', 'b = 1.50']"  ['c = 1.20']
Sam  true  true  ['d = 1.60']                ['c = 1.40']

Is there a way to remove the [] and ' besides using the find and replace function in Excel? 除了在Excel中使用查找和替换功能之外,是否还有其他方法可以删除[]'

join the items in the list and update the dictionary. join列表中的项目并更新字典。 The joining should be done with a semi-colon, to avoid moving items to the next column or having them wrapped with " " : 连接应使用分号进行,以避免将项目移至下一列或将其用" "包裹:

header = ['Name', 'Hp', 'Wife', 'Car', 'House']
with open("output.csv", "w") as f:
    w = csv.DictWriter(f, header)
    w.writeheader()
    for key, val in sorted(d.items()):
        row = {'Name': key}
        row.update(val)
        row['Car'] = '; '.join(row['Car'])  # here
        row['House'] = '; '.join(row['House']) # here
        w.writerow(row)

Here is a way to do it by using str.join() to join the items in the nested lists. 这是一种通过使用str.join()嵌套列表中的项目的方法。 The nested lists are detected using isinstance() . 使用isinstance()检测嵌套列表。 If you do not specify a delimiter when creating the csv writer, it will default to comma so this code: 如果在创建csv编写器时未指定定界符,则它将默认为逗号,因此此代码:

import csv

d = {'Bob': {'Car': ['a = 1.10', 'b = 1.50'],
         'House': ['c = 1.20'],
         'Hp': 'true',
         'Wife': 'false'},
     'Sam': {'Car': ['d = 1.40'],
         'House': ['c = 1.60'],
         'Hp': 'true',
         'Wife': 'true'}}

header = ['Name', 'Hp', 'Wife', 'Car', 'House']

with open("output.csv", "w") as f:
    w = csv.DictWriter(f, header)
    w.writeheader()
    for name in sorted(d):
        values_dict = {k: v if not isinstance(v, list) else ', '.join(v)
                            for k,v in d[name].items()}
        w.writerow(dict(Name=name, **values_dict))

will output 将输出

Name,Hp,Wife,Car,House
Bob,true,false,"a = 1.10, b = 1.50",c = 1.20
Sam,true,true,d = 1.40,c = 1.60

to the csv file. 到csv文件。 Notice that there are embedded quotes in the output. 请注意,输出中包含嵌入式引号。 This is so that Excel will not interpret the inner , as a delimiter, and Excel will not display the quotes when the file is loaded. 这是为了让Excel将不解释内,作为分隔符,并在加载文件时,Excel将不显示引号。 It's fine to leave it there. 放在那里就好了。

If you don't like that you can change the csv delimiter to a space for example: 如果您不喜欢,可以将csv分隔符更改为空格,例如:

w = csv.DictWriter(f, header, delimiter=' ')

Or you could use a different delimiter when joining the items in the nested lists. 也可以在将嵌套列表中的项目加入时使用其他定界符。

x = ['a = 1.10', 'b = 1.50']
print x
print str(x).replace('[','').replace(']','').replace("'",'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM