noname292123
noname292123

Reputation: 5

Python saving to a file all keys to a value on the same line

Ok so I am trying to save all the keys that as the same value on the same line.

lista = {'Cop': '911', 'Police chief': '911'}
spara = lista
fil = open("test" + ".txt","w")
print "savin to file "
for keys, values in spara.items():
    spara_content = spara[keys] + ";" + keys
    fil.write(spara_content)
    fil.write(";")
    fil.write("\n")
fil.close()
print lista

The code saves like this right now

911;Cop;
911;Police chief;

But i need the code to be like this when a key has the same value.

911;Cop;Police chief;

Upvotes: 0

Views: 55

Answers (2)

randomir
randomir

Reputation: 18697

Sort lista dictionary items list by value (like 911), then iterate over all groups with the same value (like 911), and then just join/print all keys in each group (with group-unique value prepended):

>>> from operator import itemgetter
>>> from itertools import groupby
>>> lista = {'Cop': '911', 'Police chief': '911'}
>>> [";".join([k]+[v[0] for v in vs]) for k,vs in groupby(sorted(vals.items(), key=itemgetter(1)), itemgetter(1))]
['911;Cop;Police chief']

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

lista = {'Cop': '911', 'Police chief': '911'}
from collections import defaultdict
d = defaultdict(list)
fil = open("test.txt","w")
for a, b in lista.items():
   d[b].append(a)
for a, b in d.items():
   fil.write(a+';'+';'.join(b)+"\n")
fil.close()

Upvotes: 0

Related Questions