Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an alternating dictionary with a loop in Python

I'm trying to create a dictionary with a loop, with alternating entries, although the entries not necessarily need to be alternating, as long as they are all in the dictionary, I just need the simplest solution to get them all in one dictionary. A simple example of what I'm trying to achieve:

Normally, for creating a dictionary with a loop I would do this:

{i:9 for i in range(3)}
output: {0: 9, 1: 9, 2: 9}

Now I'm trying the follwing:

{i:9, i+5:8 for i in range(3)}
SyntaxError: invalid syntax

The desired output is:

{0:9, 5:8, 1:9, 6:8, 2:9, 7:8}

Or, this output would also be fine, as long as all elements are in the dictionary (order does not matter):

{0:9, 1:9, 2:9, 5:8, 6:8, 7:8}

The context is that I'm using

theano.clone(cloned_item, replace = {replace1: new_item1, replace2: new_item2})

where all items you want to replace must be given in one dictionary.

Thanks in advance!

like image 904
User01 Avatar asked Jul 30 '26 20:07

User01


1 Answers

You can pull this off in a single line with itertools

dict(itertools.chain.from_iterable(((i, 9), (i+5, 8)) for i in range(3)))

Explained:

The inner part creates a bunch of tuples

((i, 9), (i+5, 8)) for i in range(3)

which in list form expands to

[((0, 9), (5, 8)), ((1, 9), (6, 8)), ((2, 9), (7, 8))]

The chain.from_iterable then flattens it by a level to produce

[(0, 9), (5, 8), (1, 9), (6, 8), (2, 9), (7, 8)]

This of course works with the dict init that takes a sequence of tuples

like image 136
Ryan Haining Avatar answered Aug 01 '26 09:08

Ryan Haining



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!