Creating an alternate dictionary with a loop in Python

I'm trying to create a looping dictionary with alternating entries, although the entries don't have to alternate if they are all in the dictionary, I just need the simplest solution to get them all into one dictionary. A simple example of what I am trying to achieve:

Usually, to create a dictionary with a loop, I would do the following:

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

      

Now I am trying to do the following:

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

      

Desired result:

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

      

Or this output will also be fine as long as all the elements are in the dictionary (order doesn't matter):

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

      

In context, I am using

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

      

where all the elements you want to replace must be in the same dictionary.

Thanks in advance!

+3


source to share


2 answers


Understanding is great, but not necessary. In addition, there are no duplicate keys in standard dictionaries. There are data structures for this, but you can also try having list

values ​​for this key:

d = {}
d[8] = []
for i in range(3):
    d[i] = 9
    d[8].append(i)

      

 

>>> d
{8: [0, 1, 2], 0: 9, 2: 9, 1: 9}

      



For your new example, without duplicate keys:

d = {}
for i in range(3):
    d[i] = 9
    d[i+5] = 8

      

 

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

      

+2


source


You can turn this off in one line with itertools

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

      


Clarifications:

Inner part creates a bunch of tuples

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

      



which expands as a list to

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

      

chain.from_iterable

then levels it down, creating

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

      

This of course works with dict

init, which takes a sequence of tuples

+3


source







All Articles