如何使用Python在CSV中使用元组值编写键

时间:2019-05-17 00:15:39

标签: python dictionary export-to-csv

我想使用Python在CSV文件中编写具有元组值的特定键。我目前无法使用numby或任何其他python外部库。我正在使用“ zip”来实现此目的,但是只有与键相关联的第一个值才被定向,而我想在元组中打印所有值。 下面提供了示例字典和代码:

data = {
    "Pakistan": (0.57, 0.05, 0.79),
    "India": (0.47, 0.12, 0.54),
    "Bangladesh": (0.49, 0.17, 0.81)
    }
con_name = input("Write up to three comma-separated countries for which you want to extract data: ")
count = len(re.findall(r'\w+', con_name))
if count == 1:
    con_check1 = con_name.split()[0]
    if con_check1.lower() in map(str.lower, data.keys()):
        con_check1 = con_check1.capitalize()
        x = list(data.keys()).index(con_check1)
        y = [key for key in data.keys()][x]
        csv_columns = ['Country Name','1997','1998','1999']
        with open('Emissions_subset.csv','w') as out:
            csv_out=csv.writer(out)
            csv_out.writerow(csv_columns) 
            z = [y]
            csv_out.writerows(zip(z, data[con_check1]))

CSV文件中的当前输出:

Country Name, 1997, 1998, 1999
Pakistan      0.57

所需的输出:

Country Name, 1997, 1998, 1999
Pakistan      0.57, 0.05, 0.79

您能帮我解决这个问题吗?我最近一直在问一些问题,没有人回答我。我真的被困在这里,只在精疲力尽之后才问一个问题。

1 个答案:

答案 0 :(得分:2)

尝试一下:

   [In]    kv_list = [[key,*val] for key, val in data.items()]
   [In]   print(kv_list)
   [Out]  [['Pakistan', 0.57, 0.05, 0.79], ['India', 0.47, 0.12, 0.54], ['Bangladesh', 0.49, 0.17, 0.81]]

然后只使用csv_out.writerows(kv_list)