将键值对转换为字符串

时间:2020-03-25 06:14:28

标签: python

我正在尝试将键值对从csv文件转换为字符串并将其附加。

链接到csv文件:Click Here

我正在尝试将其格式化为: {“ ABC”:“ 43”,“ DEF”:“ 33”} 并将其存储为字符串。

这基本上是为Notes(密钥)和1996年(值)附加键值对

我尝试过的代码段:

fin=''
x=''
input_file = csv.DictReader(open("salesexample.csv"))
for row in input_file:
    #x=print('"'+str(row['Notes'])+'"',':'+'"'+str(row['1996'])+'",')
    for row in input_file:
        cont=str(row['Notes'])
        year=str(row['1996'])
        x=x+'"'+cont+'":'+'"'+year+'",'
    fin='{'+x+'}'
    print(fin)

但是运行上面的代码会引发错误,例如无法将元组转换为字符串。 请帮忙。

3 个答案:

答案 0 :(得分:0)

不能完全确定您要做什么,但是对于这样的事情,我更喜欢使用Pandas。

例如:

import pandas as pd

df = pd.read_csv("salesexample.csv")

cont = df['Notes'].to_list()
years = df.columns[1:].to_list()

for year in years:
    your_dict = {c:str(y) for (c,y) in zip(cont,df[year])}
    your_dict_string = f"{your_dict}" # optional, if you really need it to be a string
    print(f"{year} : {your_dict_string}")

这将输出以下输出:

1990 : {'ABC': '200', 'DEF': '11'}
1991 : {'ABC': '134', 'DEF': '9'}
1992 : {'ABC': '156', 'DEF': '12'}
1993 : {'ABC': '564', 'DEF': '-'}
1994 : {'ABC': '12', 'DEF': '12'}
1995 : {'ABC': '43', 'DEF': '67'}
1996 : {'ABC': '43', 'DEF': '33'}

自然地,您可以将每个your_dict / your_dict_string变量附加到for循环内的列表中,以备后用。

答案 1 :(得分:0)

您不需要嵌套的循环。仅1个循环就足以获得所需的结果。以下代码可在Python3中使用:

fin=''
x=''
input_file = csv.DictReader(open("salesexample.csv"))
for row in input_file:
    #x=print('"'+str(row['Notes'])+'"',':'+'"'+str(row['1996'])+'",')
      cont=str(row['Notes'])
      year=str(row['1996'])
      x=x+'"'+cont+'":'+'"'+year+'",'
fin='{' + x
fin=fin[:-1] + '}'
print(fin)

输出:{"ABC":"43","DEF":"33"}

答案 2 :(得分:0)

您可以简单地做到这一点

import pandas as pd
df = pd.read_csv("salesexample.csv")
result = dict(zip(df["Notes"],df["1996"]))
相关问题