First of all, i’m sure that the title is a bit confusing, but I couldn’t think of a good way to state in a few words the scope of a solution I was looking for today. Basically, I had a list of dictionaries and I wanted to create a new list of dictionaries with an additional key-value pair. For example, let’s say I have a list of dictionaries which define a and b:


my_list = [
    { 'a': 1, 'b': 2 },
    { 'a': 2, 'b': 3 },
    { 'a': 3, 'b': 4 }
]

What I wanted to do was create a new list containing copies of the dictionaries with a new key-value pair. After finding this stackoverflow answer I came up with a solution similar to the following:


import math
list1 = [
    {'a': 1, 'b': 2},
    {'a': 2, 'b': 3},
    {'a': 3, 'b': 4}
]
list2 = [dict(d.items() + [('c', math.hypot(*d.values()))]) for d in list1]
# [
#     {'a': 1, 'c': 2.23606797749979, 'b': 2},
#     {'a': 2, 'c': 3.605551275463989, 'b': 3},
#     {'a': 3, 'c': 5.0, 'b': 4}
# ]

Cool stuff, right? Do you know what is actually happening? d.items() actually turns each key-value pair into a tuple and returns them all as a list. Then we are concatenating our tuple to make a new list of three tuples. In this case doing math.hypot(*args) actually passes each item in the list as a separate argument (here is more information about using an apply-like function in Python). After that dict(...) takes that list of tuples and creates a dictionary from them. Finally, this is done for each dictionary in list1, add the new dictionary to a new list which is assigned to list2.

How cool is that?!?!?! Even though I still am a big fan of JavaScript, the fact that you can write this type of code in Python is pretty inspiring! šŸ˜Ž

Categories: BlogPython

Leave a Reply

Your email address will not be published. Required fields are marked *