Rahimi0151
Rahimi0151

Reputation: 411

How to break a dictionary into a list of dictionaries in python?

I'm trying to convert a dictionary into a list, which contains many dictionaries. for example:

input:

{
    'first-name':'foo',
    'last-name':'bar',
    'gender':'unknown',
    'age':99
}

output:

[{'first-name': 'foo'}, {'last-name': 'bar'}, {'gender': 'unknown'}, {'age':99}]

I am already using this code to do such:



def convert(info: dict):
    new_list = list

    for item in info:
        new_parameter = {item:info[item]}
        new_list.append(new_parameter)

    return new_list

but I was wondering if there is a built-in function to do this? or a more readable piece of code? it's almost 10 lines! and kind of confusing to understand!

Upvotes: 3

Views: 1523

Answers (5)

sahasrara62
sahasrara62

Reputation: 11228

k={
    'first-name':'foo',
    'last-name':'bar',
    'gender':'unknown',
    'age':99
}

s =list(map(lambda x:{x[0]:x[1]},k.items() ))

output

[{'first-name': 'foo'},
 {'last-name': 'bar'},
 {'gender': 'unknown'},
 {'age': 99}]

Upvotes: 0

Spark
Spark

Reputation: 2487

Dict = {
    'first-name':'foo',
    'last-name':'bar',
    'gender':'unknown',
    'age':99
}
list = [(key, value) for key, value in Dict.items()]

list >> [('first-name':'foo'), ('last-name':'bar'), ('gender':'unknown'),('age':99)]

This is the simplest way to Convert dictionary to list of tuples

Reference : Python | Convert dictionary to list of tuples

Upvotes: 1

bharatk
bharatk

Reputation: 4315

Using list comprehension

  • items() method is used to return the list with all dictionary keys with values.

Ex.

dict1 = {
    'first-name':'foo',
    'last-name':'bar',
    'gender':'unknown',
    'age':99
}

new_list = [{k:v} for k,v in dict1.items() ]
print(new_list)

O/P:

[{'first-name': 'foo'}, {'last-name': 'bar'}, {'gender': 'unknown'}, {'age': 99}]

Another solution suggested by @josoler

new_list = list(map(dict, zip(dict1.items())))

Upvotes: 6

Selcuk
Selcuk

Reputation: 59184

An alternative method:

>>> [dict([i]) for i in d.items()]
[{'gender': 'unknown'}, {'age': 99}, {'first-name': 'foo'}, {'last-name': 'bar'}]

Upvotes: 0

Fedor Dikarev
Fedor Dikarev

Reputation: 506

>>> d={
...     'first-name':'foo',
...     'last-name':'bar',
...     'gender':'unknown',
...     'age':99
... }
>>> [{k: v} for (k, v) in d.items()]
[{'first-name': 'foo'}, {'last-name': 'bar'}, {'gender': 'unknown'}, {'age': 99}]

Upvotes: 0

Related Questions