sruthi
sruthi

Reputation: 165

How to convert list of dictionaries to list of tuples?

I have a list of dictionaries in python like:

lst = [{'f_id': '1', 'm_id':'22', 'fm_id':'23'},{'f_id': '2', 'm_id':'32', 'fm_id':33}]

I'm trying to update the values in dictionary like lst = [{'f_id': '3', 'm_id':'22', 'fm_id':'N'},{'f_id': '4', 'm_id':'32', 'fm_id':N}]

and get only values from dictionary and put them in list of tuples like:

new_lst = [('3', '22', 'N'),('4', '32', 'N')]

I've tried:

list_of_dict = []
for each in lst:
    for key, values in each.items():
        temp = values
        list_of_dict.append(temp)
    print(list_of_dict)

but I'm getting a different output. I'm tried different approaches but not getting the expected output.

Upvotes: 0

Views: 360

Answers (2)

user15801675
user15801675

Reputation:

Here is a one liner solution:

j=[tuple([str(x) for x in d.values()]) for d in lst ]

Output:

[('1', '22', '23'), ('2', '32', '33')]

Upvotes: 0

vht981230
vht981230

Reputation: 5071

Have you tried this?

lst = [{'f_id': '1', 'm_id':'22', 'fm_id':'23'},{'f_id': '2', 'm_id':'32', 'fm_id': '33'}]
new_lst = [tuple(d.values()) for d in lst]

Upvotes: 2

Related Questions