Py学习  »  Python

将python字典组合成字符串csv

Evan Graves • 5 年前 • 1674 次点击  

我这里有本字典:

dict = {'AB': 1, 'AE': '0', 'CC': '3'}

我正试着把字典转换成字符串格式:

AB1,AE0,CC3

我目前正在尝试:

string = ",".join(("{},{}".format(*i) for i in dict.items()))

但我的成果是:

AB,1,AE,0,CC,3

只是稍微差了一点。

有人知道如何将这本字典正确地格式化成字符串吗?

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44297
 
1674 次点击  
文章 [ 5 ]  |  最新文章 5 年前
cph_sto
Reply   •   1 楼
cph_sto    6 年前

其思想是循环遍历字典的每个元素,然后将其键和值连接在一起。最后,将这个连接的值追加到列表中。

d = {'AB': 1, 'AE': '0', 'CC': '3'}

#initialize an empty list
l=[]
for i in d:
    l.append(str(i)+str(d[i]))

一旦获得此列表,只需使用join()函数将其转换为一个字符串,其元素用逗号分隔。

out = ','.join(l)
print(out)
   'AB1,AE0,CC3' 
Reut Sharabani
Reply   •   2 楼
Reut Sharabani    6 年前

更实用的解决方案:

# don't shadow `dict`
d = {'AB': 1, 'AE': '0', 'CC': '3'}

# `starmap` flattens argument to a function
# needed for `str.format`
from itertools import starmap

# build parts from dictionary items
parts = starmap('{}{}'.format, d.items())

# build end result from parts
result = ','.join(parts)

如果你想要一个健壮的解决方案,你应该使用 csv 模块并查看 DictWriter

Daweo
Reply   •   3 楼
Daweo    6 年前

如果使用python 3,则可以使用所谓的f字符串:

d = {'AB': 1, 'AE': '0', 'CC': '3'}
out = ','.join([f'{i}{d[i]}' for i in d.keys()])
print(out)

输出:

AB1,AE0,CC3

如果你想知道更多关于f字符串的信息,请看这个 tutorial . 请记住,此解决方案仅适用于Python3.3和更新版本。

Igor Dragushhak
Reply   •   4 楼
Igor Dragushhak    6 年前

代码:

dict = {'AB': 1, 'AE': '0', 'CC': '3'}
string=','.join([i+str(dict[i]) for i in dict])
print(string)

输出:

AB1,AE0,CC3
Jan
Reply   •   5 楼
Jan    6 年前

开始了(删除逗号):

d = {'AB': 1, 'AE': '0', 'CC': '3'}

output = ",".join(["{}{}".format(key, value) for key, value in d.items()])
#                   ^^^^
print(output)

这个产量

AB1,AE0,CC3

或者使用原始的解包方法:

output = ",".join(["{}{}".format(*x) for x in d.items()])

另外,请不要在内置对象(dict、list、tuple等)之后命名变量。