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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With