Create a new dictionary with the key-value pair from values in a list of dictionaries based on matches from a separate list

I am trying to get a new dictionary with the k: v pair from values in a list of dictionary based on matches from a separate list.

The casing is different.

My data looks like this:

list_of_dicts = [   
{'fieldname': 'Id', 'source': 'microsoft', 'nullable': True, 'type': 'int'},
{'fieldname': 'FirstName', 'source': 'microsoft', 'nullable': True, 'type': 'string'},
{'fieldname': 'LastName', 'source': 'microsoft', 'nullable': False, 'type': 'string'},
{'fieldname': 'Address1', 'source': 'microsoft', 'nullable': False, 'type': 'string'}
                ]
fieldname_list = ['FIRSTNAME', 'LASTNAME']

From this I would like to create a new dictionary as follows:

new_dict = {'FirstName': 'string', 'LastName': 'string'}

I think this should be possible with a dictionary comprehension, but I can’t work it out – can anyone help?

>Solution :

Do you want to do?

list_of_dicts = [
{'fieldname': 'Id', 'source': 'microsoft', 'nullable': True, 'type': 'int'},
{'fieldname': 'FirstName', 'source': 'microsoft', 'nullable': True, 'type': 'string'},
{'fieldname': 'LastName', 'source': 'microsoft', 'nullable': False, 'type': 'string'},
{'fieldname': 'Address1', 'source': 'microsoft', 'nullable': False, 'type': 'string'}
                ]
fieldname_list = ['FIRSTNAME', 'LASTNAME']
new_dict = {x['fieldname']: x['type']  for x in list_of_dicts if x['fieldname'].upper() in fieldname_list}
print(new_dict)
# output: {'FirstName': 'string', 'LastName': 'string'}

Leave a Reply