How to Insert Each Dictionary Value into a List After the Corresponding Key?

2020-05-23 python list dictionary list-comprehension data-manipulation

I have a list of elements and I'd like to insert dictionary values into that list after the key element:

listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}

giving the following:

['a', 'b', 'x', 'c', 'd', 'y']

What is the Pythonic way to do this?

Answers

The correct way:

import itertools

listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}

new_map = ([m, some_new_elements[m]] if m in some_new_elements else [m] for m in listicle)
print(list(itertools.chain.from_iterable(new_map)))
>>> ['a', 'b', 'x', 'c', 'd', 'y']

A simple way to do that without list comprehension:

listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}

output = []
for x in listicle:
    output.append(x)
    if(x in some_new_elements):
        output.append(some_new_elements[x])

print(output)
>>>['a', 'b', 'x', 'c', 'd', 'y']

Try to use itertools.chain.from_iterable which is like a flatmap:

from itertools import chain
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
output = list(chain.from_iterable([[x, some_new_elements[x]] if x in some_new_elements else [x] for x in listicle]))
print(output) # output:  ['a', 'b', 'x', 'c', 'd', 'y']

Here is a comprehension to do this:

>>> listicle = ['a', 'b', 'c', 'd']
>>> some_new_elements = {'b':'x', 'd':'y'}
>>> sentinel=object()
>>> [x for t in ((e, some_new_elements.get(e, sentinel)) for e in listicle) for x in t if x !=sentinel]
['a', 'b', 'x', 'c', 'd', 'y']

Related