0

I like to enclose the value of dictionary of dictionary inside a list and which should be further enclosed inside a tuple,I'm able to enclose the value inside a list but I'm unable to enclose it inside a tuple.

(Pdb) ase={'apple':{'ball':9}}
(Pdb) ase['apple']=[ase['apple']]
(Pdb) p ase
{'apple': [{'ball': 9}]}
(Pdb) ase['apple']=(ase['apple'])
(Pdb) p ase
{'apple': [{'ball': 9}]}

1 Answers1

0

From Python docs:

The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().)

from collections import defaultdict
dict_d = {'apple':{'ball':9}}
weird_dict = defaultdict()
for k, v in dict_d.items():
    weird_dict[k] = ([v],) #trailing comma is required if tuple has only one element

print(weird_dict)
# defaultdict(None, {'apple': ([{'ball': 9}],)}) 

#print(weird_dict['apple'])
jpp
  • 159,742
  • 34
  • 281
  • 339
Tanmay jain
  • 814
  • 6
  • 11