Python字典串

时间:2013-08-14 13:04:00

标签: python string dictionary

在单个字符串中转换Python dict的正确方法是什么?

我有代码的示例程序:

keywordsList = {u'roland.luethe1@gmail.com': 2, u'http://www.3ho.de/': 4, u'http://www.kundalini-yoga-zentrum-berlin.de/index.html': 1, u'ergo@ananda-pur.de': 3}

keywordsCount = sorted(keywordsList.items(),key=lambda(k,v):(v,k),reverse=True)

for words in keywordsCount:
    print words[0], " - count: ", words[1]

所以在我对项目进行排序后,得到的结果如下:

http://www.3ho.de/  - count:  4
ergo@ananda-pur.de  - count:  3
roland.luethe1@gmail.com  - count:  2
http://www.kundalini-yoga-zentrum-berlin.de/index.html  - count:  1

我的问题是将所有dict内容与cout组合在一个单独的字符串中的正确方法是什么,它看起来像是打印出来的:

'http://www.3ho.de/ : 4, ergo@ananda-pur.de : 3, roland.luethe1@gmail.com : 2, http://www.kundalini-yoga-zentrum-berlin.de/index.html : 1'

或类似但以逻辑方式?

3 个答案:

答案 0 :(得分:2)

明智地使用str.join()

', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)])

输出:

>>> ', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)])
u'http://www.3ho.de/ : 4, ergo@ananda-pur.de : 3, roland.luethe1@gmail.com : 2, http://www.kundalini-yoga-zentrum-berlin.de/index.html : 1'

你应该真正研究collections.Counter()并保存自己不得不那样排序。 Counter.most_common()方法按频率按反向排序顺序列出项目。

答案 1 :(得分:0)

我不确定正确的方法,但你也可以这样做:

', '.join(' : '.join([a, str(b)]) for a, b in keywordsCount)

答案 2 :(得分:0)

使用传统方法,这很简单。这对我有用

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
d=" " 
for  i in dict:
 a=i
 b=dict[i]
 c=i+":"+dict[i]
 d=d+c+'\n'

print d