I have a list of dictionary like below :
sample = [{'By': {'email': '[email protected]', 'name': 'xyzzy', 'id': '5859'}},{'By': {'email': '[email protected]', 'name': 'abccb', 'id': '9843'}},
{'By': {'email': '[email protected]', 'name': 'xyzzy', 'id': '5859'}}]
From this, I am trying to access keys 'name' and 'id' and write distinct values into a dictionary.
Below is returning id's alone :
print(set(map(lambda x: x['By']['id'], sample)))
output: {'9843', '5859'}
Required output : {"9843":"abccb", "5859":"xyzzy"}
I tried with f-string to concatenate the 'id' and 'name' values with a colon (:) in between to give in the format "id:name" for each dictionary item in the list.
set(map(lambda x: f"{x['By']['id']}:{x['By']['name']}", sample))
output : {'9843:abccb', '5859:xyzzy'}
Is it possible to access values of two keys in the map lambda function ? Thank you.
You want a dict
, not a set
. You can get all the values in the lambda
and pack them in a tuple
print(dict(map(lambda x: (x['By']['id'], x['By']['name']), sample)))
You should also consider a simpler solution, you don't really need map
and lambda
here, dict-comprehensions will do just fine
print({x['By']['id']: x['By']['name'] for x in sample})