[英]I want to convert dictionary with tuples as keys to specific format and then store it in a file
[英]python different number of keys dictionary store to text file in specified format
我有一個字典,格式如下frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2, '3'): 5}
etc. 我想將它存儲在output.txt中,格式如下。
預期結果
11 (23)
23 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)
我寫了這個:
with open('output.txt', 'w') as file:
for k, v in frequent_itemset.items():
file.write("{} ({}) \n".format(" ".join(map(str, k)), v))
結果:
1 1 (23)
1 2 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)
您混淆了 map,因為字符串被認為是可迭代的以及元組/列表。
例如,如果你遍歷一個包含["a", "b", "c"]
的列表,你會得到"a", "b", "c"
。 然而,如果你遍歷一個字符串"abc"
,你也會得到"a", "b", "c"
。
試試這個...
frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2', '3'): 5}
for k,v in frequent_itemset.items():
if isinstance(k, (list, tuple)):
key = ' '.join([x for x in k])
else:
key = k
print("{} ({})".format(key,v))
frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2', '3'): 5}
for k,v in frequent_itemset.items():
print(*k, '({})'.format(v)) if isinstance(k, tuple) else print(k,'({})'.format(v))
output
11 (23)
23 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)
一個簡單for
循環:
for x,y in frequent_itemset.items(): print((x if type(x)==str else " ".join(x)) + " (" + str(y) + ")" )
一個班輪:
[print((x if type(x)==str else " ".join(x)) + " (" + str(y) + ")" ) for x,y in frequent_itemset.items()]
結果
11 (23) 23 (20) 20 32 (10) 2 3 (9) 1 2 3 (5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.