Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List Comprehension Format for Dictionaries

I have a dictionary that has three categories for my customers, and there are multiple customers under each category:

ddd = {'category 1:': 
         {'A': 50.5,
          'B': 28.9,
          'C': 46.3,
          'D': 513.8},
       'category 2:': {'E': 20.5, 'C': 48.1},
       'category 3:': {'D': 28.2, 'F': 68.3}}

The number in each sub-dictionary represents the dollar amount they paid. Therefore, I want to convert all the number into string dollar amount format with two decimal places like ‘A’: 50.5 -> ‘A’: ‘$50.50’. The ideal output will be:

{'category 1:': {'A': '$50.50', 'B': '$28.90', 'C': '$46.30', 'D': '$513.80'}, 'category 2:': {'E': '$20.50', 'C': '$48.10'}, 'category 3:': {'D': '$28.20', 'F': '$68.30'}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my solution to this:

for a,b in ddd.items():
    for i,j in b.items():
        b[i] = "$" + "{0:,.2f}".format(j)

This will work, but I want to learn if it is possible to write the above nested for loop into a format similar to a one-liner list comprehension format.
I tried

{a:b for i,("$" + "{0:,.2f}".format(j)) in b.items() for a,b in ddd.items()} 

but this doesn’t seem work. Thank you in advance!

Writing codes in a simplified format.

>Solution :

Like this?

ddd = {k: {ik: "$" + "{0:,.2f}".format(v) for ik, v in v.items()} for k, v in ddd.items()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading