-1

The example code -

innerdict = {}
outerdict = {}
for line in range(1, 10, 2):
    for j in range(1, 10, 2):
        line_tuple = ("Item" + str( line ), int( line ))
        key = line_tuple[1]
        if line ==j:
           outerdict[key] = dict( innerdict )
           outerdict[key] = {'Name': '{0}'.format( "item"+str(j) ), 'Price': '{0}'.format( j )}
print(outerdict)

The ouput comes out like this-

{1: {'Name': 'item1', 'Price': '1'}, 3: {'Name': 'item3', 'Price': '3'}, 5: {'Name': 'item5', 'Price': '5'}, 7: {'Name': 'item7', 'Price': '7'}, 9: {'Name': 'item9', 'Price': '9'}}

The above output is achievable since it is conventional. I found a lot of online suggestions regarding nested dictionary comprehension.

But I want the output to come out like below-

{{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'},  {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}

Thanks in advance!

2 Answers2

0

What you want is something like a list of dictionaries. And this {{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'}, {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}} is invalid as dictionary is considered to be a key-value pair and there is no key in this.

It can be checked by assigning the above to a variable and then checking its type.

d = {{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'},  {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}
print(type(d))

It will result in an error saying it's unhashable.

luctivud
  • 76
  • 7
0

This is not possible, as the dict objects are not hashable.

{{1:2}} would mean putting a dict {1:2} into a set, which is not possible because of the un-hashability of the objects mentioned above. Better put them in a list:

[{1:2}, {2:3}]

mabergerx
  • 1,216
  • 7
  • 19