NGuyen
NGuyen

Reputation: 275

Python 3: How to convert array to list of dictionary?

def get_list(name, ids):
    single_database = {}  
    database = [] 
    for id in ids:
        single_database['id'] = id
        single_database['name'] = name
        database.append(single_database.copy()) 

    return database

input = [{'name': 'David', 'id': ['d1','d2']},
            {'name':'John', 'id': ['j1','j2']}]

for single_database in input:
        get_list(single_database['name'], single_database['id'])

Hello, I want to convert the above "input" array to list of dictionary, so I wrote the code to convert them. However, "get_list" function only release the last dictionary. So, how to get all list of dictionary and keep using "get_list" function. Also, except my way, there is any way to convert this input faster ?

This is the output I want:

{'id': 'd1', 'name': 'David'}
{'id': 'd2', 'name': 'David'}
{'id': 'j1', 'name': 'John'}
{'id': 'j2', 'name': 'John'}

Upvotes: 0

Views: 239

Answers (2)

Rahul K P
Rahul K P

Reputation: 16081

You can build this in single line of code, Beauty of python

result = [{'id':j,'name':i['name']} for i in input_dict for j in i['id']]

Result

[{'id': 'd1', 'name': 'David'},
 {'id': 'd2', 'name': 'David'},
 {'id': 'j1', 'name': 'John'},
 {'id': 'j2', 'name': 'John'}]

Upvotes: 2

georg
georg

Reputation: 214959

This should work

list_of_dicts = [
    {'id': id, 'name': d['name']}
    for d in input
    for id in d['id']
]

or in a more verbose form:

def get_list(input):

    list_of_dicts = []

    for d in input:
        for id in d['id']:
            list_of_dicts.append({
                'id': id, 
                'name': d['name']
            })        

    return list_of_dicts

In general, try to avoid temporary variables (like your single_database) and use literals instead.

Also, input is a poor choice for a variable name, since it hides an important built-in.

Upvotes: 8

Related Questions