Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a better way to create a dictionary with key and value from a list of dictionaries dynamically?

input:

input = [
    {'key': '1', 'value': 'a'},
    {'key': '2', 'value': 'b'},
    {'key': '3', 'value': 'c'}
]

output

{
    "1": "a",
    "2": "b",
    "3": "c"
}

What I’ve tried:

output = {list(entry.values())[0]: list(entry.values())[1] for entry in input}
print(output) #{'1': 'a', '2': 'b', '3': 'c'}

My question is there a better way of doing this instead of each entry get list of values and access to the first or second!

Any suggestion of doing it in a more simple way!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As entry is a dict, access the data using the keys, that is how you should manipulate a dict

values = [
    {'key': '1', 'value': 'a'},
    {'key': '2', 'value': 'b'},
    {'key': '3', 'value': 'c'}
]

output = {entry['key']: entry['value'] for entry in values}

input is the python builtin method for reading user input, don’t use it as a variable name

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading