-3

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?

alexei7
  • 182
  • 1
  • 3
  • 11

1 Answers1

1

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'}
Sezer BOZKIR
  • 534
  • 2
  • 13