3

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!

User01
  • 99
  • 7

2 Answers2

3

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

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
2

Comprehensions are cool, but not strictly necessary. Also, standard dictionaries cannot have duplicate keys. There are data structures for that, but you can also try having a list of values for that 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}
Community
  • 1
  • 1
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97