user3271404 user3271404 - 1 month ago 8
Python Question

How to remove the all the curly bracket in dictionary of dictionaries

I wish to remove all the curly brackets from my current output. My current output as shown below:

{'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ
SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1
}}


My current code as shown below:

for merchant, product, quantity in big_list:
d[merchant][product] += quantity

print ({ k:dict(v) for k,v in d.items() })


My desired output:

'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ
SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1


As I am still new to python, may I ask if i wish to remove the all the curly brackets in the dictionary of dictionaries. Would my desired output be achievable? If so, how should I go about doing it? Any suggestions / ideas would be appreciated. Thank you.

Answer

You can do this by converting the dictionary first to a string and then replacing all the brackets with empty strings:

d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQSEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}}

print(str(d).replace("{","").replace("}", ""))

which will print what you are looking for:

'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQSEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1