0

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

Ken Ist
  • 79
  • 6
  • 5
    What happened to `[1999, student, 6]`? – MattDMo Aug 10 '22 at 16:14
  • 2
    Why are you using a dict for this purpose? – duckboycool Aug 10 '22 at 16:14
  • I sorted it from array by loop – Ken Ist Aug 10 '22 at 16:15
  • 1
    I get the unique year requirement, but why `teacher` for `field1` and not `student`. why does teacher/5 win over student/6? Is the sort on field2, where the min(field2) for each distinct year is the winner? – JNevill Aug 10 '22 at 16:16
  • Does this answer your question? [Make a dictionary with duplicate keys in Python](https://stackoverflow.com/questions/10664856/make-a-dictionary-with-duplicate-keys-in-python) – puncher Aug 10 '22 at 16:17
  • Why create keys that have no meaning? `"field1"` has no meaning therefore just using a list would make more sense with this context. – Jab Aug 10 '22 at 16:23

2 Answers2

1

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)}
MBarsi
  • 2,417
  • 1
  • 18
  • 18
0

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}}
funnydman
  • 9,083
  • 4
  • 40
  • 55