简体   繁体   English

Python使用writerow将具有不同值类型的两个词典编写到单个csv文件中

[英]Python writing two dictionaries with different value types into a single csv file using writerow

I have two dictionaries similar to samples below: 我有两个类似于以下示例的词典:

# First dictionary
dict_names = {}
dict_names[1] = 'Jane'
dict_names[2] = 'Alex'
dict_names[3] = 'Max'

# Second dictionary
dict_numList = {}
dict_numList[1] = [i for i in range(50)]
dict_numList[2] = [2*i for i in range(50)]
dict_numList[3] = [i*i for i in range(50)]

I would like to write to csv file where each row includes common key (in its first column, when opened using excel), string value from the first dictionary (in its second column), each element of the list value from the second dictionary (in its third column all the way to 52nd column). 我想写入csv文件,其中每行包含公共密钥(在第一列中,当使用excel打开时),来自第一个字典的字符串值(在其第二列中),来自第二个字典的列表值的每个元素(在第三列一直到第52列)。

I have attempted the code below, but it will write the entire number list into third column. 我尝试了下面的代码,但它会将整个数字列表写入第三列。

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val, [dict_numList[key][i] for i in range(0,50)]])

Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks 谢谢

SOLUTION: given the answers, I have used the code below 解决方案:给出答案,我使用了下面的代码

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val] + dict_numList[key])

If your comprehension is redundant, but keeping it for now, the following approach will suffice: 如果你的理解是多余的,但现在保持这种理解,下面的方法就足够了:

for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key][i] for i in range(0,50))
    csvwriter.writerow(row)

Really, I believe you simply need: 真的,我相信你只需要:

for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key])
    csvwriter.writerow(row)

I think the problem is you're including a list in a list: 我认为问题是你在列表中包含一个列表:

[key, val, [array of things]]

Instead of: 代替:

[key, val, thing 1, thing 2...]

You can simply append the two lists together with the + operator: 您可以简单地将两个列表与+运算符一起追加:

csvwriter.writerow([key, val] + [dict_numList[key][i] for i in range(0,50)])

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

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