Home > Mobile >  List Comprehension Format for Dictionaries
List Comprehension Format for Dictionaries

Time:12-21

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

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.

CodePudding user response:

Like this?

ddd = {k: {ik: "$"   "{0:,.2f}".format(v) for ik, v in v.items()} for k, v in ddd.items()}
  • Related