0

I have a dictionary below:

a = {'Developer': [{'id':1, 'name':'a', 'age':'11'}, {'id':2, 'name':'b', 'age':'33'}, {'id':3, 'name':'c', 'age':'34'}]}

Expected output one:

[{'id':1, 'name':'a'}, {'id':2, 'name':'b'}, {'id':3, 'name':'c'}]

Expected output two, list of ids only:

[1, 2, 3]

Code:

list_ = []
for i,j in a.items():
    d = {}
    for m in j:
        d['id'] = m['id']
        d['name'] = m['name']
        list_.append(d)
        
list_

My current out:

[{'id': 3, 'name': 'c'}, {'id': 3, 'name': 'c'}, {'id': 3, 'name': 'c'}]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

4 Answers4

1

Almost there.

Put the dict inside the loop where you iterate on items in j.

And create another list for storing the ids.

Return both the lists.

lllrnr101
  • 2,288
  • 2
  • 4
  • 15
0

You can use list comprehension for this

Getting ID and name

[{'id': dev.get('id'), 'name': dev.get('name')} for dev in a.get('Developer')]

Output

[{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]

Getting just the ID

[dev.get('id') for dev in a.get('Developer')]

Output

[1, 2, 3]
0

You can also use dictionary and list comprehension to write in a Pythonic way to get the result as:

a = {'Developer': [{'id':1, 'name':'a', 'age':'11'}, {'id':2, 'name':'b', 'age':'33'}, {'id':3, 'name':'c', 'age':'34'}]}

res = [{key: value for key, value in elt.items() if key in ['id', 'name']} for elt in a['Developer']]
print(res)

ids = [elt['id'] for elt in a["Developer"]]
print(ids)

Output:

[{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]
[1, 2, 3]
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

Please try this:

list_ = []
ids=[]
for d in a:
    for l in a[d]:
        list_.append({
            'id': l['id'],
            'name': l['name']
        })
        ids.append(l['id'])


print(list_, ids)
jyoti das
  • 226
  • 2
  • 5