student student - 26 days ago 6
Python Question

python while id is the same do something

I feel like it is something basic but somehow I don't get it. I would like to loop over a list and append all the persons to the same id. Or write to the file, it doesn't matter.

[1, 'Smith']
[1, 'Black']
[1, 'Mueller']
[2, 'Green']
[2, 'Adams']

[1; 'Smith', 'Black', 'Mueller']
[2; 'Green', 'Adams']


First I have created a list of all ids and then a I had two for-loops like this:

final_doc = []
for id in all_ids:
persons = []
for line in doc:
if line[0] == id:
persons.append(line[1])
final_doc.append(id, persons)


It takes ages. I was trying to create a dictionary with ids and then combine it somehow, but the dictionary was taking the same id only once (may be I did there something not as I should have). Now I am thinking about using while-loop. While id is still the same append persons. But it is easy to understand how to do it if it has to be, for example, while id is less than 25. But in the case "while it is the same" I am not sure what to do. Any ideas are very appreciated.

Answer

You can group them together in a dictionary.

Given

lists = [[1, 'Smith'],
         [1, 'Black'],
         [1, 'Mueller'],
         [2, 'Green'],
         [2, 'Adams'] ]

do

d = {}
for person_id, name in lists:
    d.setdefault(person_id, []).append(name)

d now contains

{1: ['Smith', 'Black', 'Mueller'], 2: ['Green', 'Adams']}

Note:

d.setdefault(person_id, []).append(name)

is a shortcut for

if person_id not in d:
    d[person_id] = []
d[person_id].append(name)

If you prefer your answer to be a list of lists with the person_id as the first item in the list (as implied in your question), change code to

d = {}
for person_id, name in lists:
    d.setdefault(person_id, [person_id]).append(name) # note [person_id] default
result = list(d.values()) # omit call to list if on Python 2.x

result contains

[[1, 'Smith', 'Black', 'Mueller'], [2, 'Green', 'Adams']]