Home > Net >  Is there a better way to create a dictionary with key and value from a list of dictionaries dynamica
Is there a better way to create a dictionary with key and value from a list of dictionaries dynamica

Time:07-12

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!

CodePudding user response:

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

CodePudding user response:

You can use operator.itemgetter to generate 2-tuples from keys 'key' and 'value'. Map the generated sequence to the dict constructor for output:

from operator import itemgetter

output = dict(map(itemgetter('key', 'value'), input))

CodePudding user response:

This works:

output = {entry['key'] : entry['value'] for entry in input}
print(output)

But as others have mentioned, don't use "input" as a variable name in python. This term is already built into python, and overwriting it may cause bugs and problems later on.

CodePudding user response:

The best way is to do:

{x["key"]: x["value"] for x in input}

But don't use input as a variable name - it overwrites the builtin Python function input.

  • Related