Home > database >  create dict from different list with first element
create dict from different list with first element

Time:08-11

I have this data:

[1999, teacher, 5]
[1999, student, 6]
[2000, doctor, 11]

I want to create dict:

{'1999': {'field1': teacher, 'field2': 5}, '2000': {'field1': doctor, 'field2': 11}}

How can I get 2 unique years from data and set it in dict?Please can anybody help to understand

CodePudding user response:

we dont know the format of the data you are having.

if you have list of lists:

data = [[1999, 'teacher', 5], [1999, 'student', 6], [2000, 'doctor', 11]]

res = {}
for record in data:
    res[str(record[0])] = {f'field{k}': v for k, v in enumerate(record[1:], start=1)}

if you have text (or file):

import io

data = io.StringIO('''[1999, teacher, 5]
[1999, student, 6]
[2000, doctor, 11]''')
res = {}
for line in data.readlines():
    record = line.replace('[', '').replace(']', '').split(',')
    res[record[0]] = {f'field{k}': v.strip() for k, v in enumerate(record[1:], start=1)}

CodePudding user response:

How about using Python's iterators, this is pure beauty:

data = [[1999, 'teacher', 5], [1999, 'student', 6], [2000, 'doctor', 11]]
print({str(next(obj)): {'field1': next(obj), 'field2': next(obj)} for obj in map(iter, data)})

Output:

{'1999': {'field1': 'student', 'field2': 6}, '2000': {'field1': 'doctor', 'field2': 11}}
  • Related