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!
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}