Home > Software design >  Python - printing list of dictionaries matching the values from a list
Python - printing list of dictionaries matching the values from a list

Time:08-19

I have a list as ,

arr = ["rajab", "vedanth", "chinmay", "vignesh"]

and a dictionary as,

elements = [
        { 'name': 'vedanth',   'age': 17, 'time_hours': 1},
        { 'name': 'rajab', 'age': 12,  'time_hours': 3},
        { 'name': 'vignesh',  'age': 21,  'time_hours': 2.5},
        { 'name': 'chinmay',  'age': 24,  'time_hours': 1.5},
    ]

I want to print the elements in the dictionary based upon the values from the list..

Output:
elements = [       
        { 'name': 'rajab', 'age': 12,  'time_hours': 3},
       { 'name': 'vedanth',   'age': 17, 'time_hours': 1},
        { 'name': 'chinmay',  'age': 24,  'time_hours': 1.5},
        { 'name': 'vignesh',  'age': 21,  'time_hours': 2.5}
    ]

How can this be done by avoiding many for loops?

CodePudding user response:

The thing you mean is sorting, here based on the index of the name in the arr list

arr = ["rajab", "vedanth", "chinmay", "vignesh"]

elements = [
    {'name': 'vedanth', 'age': 17, 'time_hours': 1},
    {'name': 'rajab', 'age': 12, 'time_hours': 3},
    {'name': 'vignesh', 'age': 21, 'time_hours': 2.5},
    {'name': 'chinmay', 'age': 24, 'time_hours': 1.5},
]

elements.sort(key=lambda item: arr.index(item['name']))

print(elements)

CodePudding user response:

I would first construct a dict that maps name to dict and then use it:

arr = ["rajab", "vedanth", "chinmay", "vignesh"]
elements = [{ 'name': 'vedanth',  'age': 17, 'time_hours': 1},
            { 'name': 'rajab', 'age': 12, 'time_hours': 3},
            { 'name': 'vignesh', 'age': 21, 'time_hours': 2.5},
            { 'name': 'chinmay', 'age': 24, 'time_hours': 1.5}]

name_to_dict = {dct['name']: dct for dct in elements}

output = [name_to_dict[name] for name in arr]
print(output)
# [{'name': 'rajab', 'age': 12, 'time_hours': 3},
#  {'name': 'vedanth', 'age': 17, 'time_hours': 1},
#  {'name': 'chinmay', 'age': 24, 'time_hours': 1.5},
#  {'name': 'vignesh', 'age': 21, 'time_hours': 2.5}]

CodePudding user response:

newElements = [x for x in elements for y in arr if y == x['name']]
  • Related