简体   繁体   中英

Dictionary help in Python3

I'm trying to print a formatted layout of a list. I've got the main part down but I can't seem to get the numbering right.

Here's the code:

shopping_list = {"eggs": "$2", "milk": "$3.50", "cereal": "$3"}

my_shopping_list = "".join(**n**+". "+item+" "+shopping_list[item]+"\n" for item in shopping_list)

print(my_shopping_list)

Basically I want to print the items and price in the format:

{number}. {item} {price}\\n

So the results should be:

1. eggs $2
2. milk $3.50
3. cereal $3

It should work if I add more items into the dictionary

But I do not know what to replace n with:

**n**+". "+item+" "+shopping_list[item]+"\n" for item in shopping_list

I've tried using lists to do this

shopping_list = [["eggs", "$2"], ["milk", "$3.50"], ["cereal", "$3"]]

my_shopping_list = "".join(str(n+1)+". "+shopping_list[n][0]+" "+shopping_list[n][1]+"\n" for n in range(len(shopping_list)))

print(my_shopping_list)

And it works just fine but I need it to work for dictionary so do I find a way to index a dictionary like a list or is there a better way to do it?

Thanks in advance!

You almost have it right. You can adapt your code to use dict.items()

my_shopping_list = "".join(str(i+1)+". "+ k + " "+ v +"\n" for i, (k,v) in enumerate(shopping_list.items()))

But I would recomend using str format, and joining using \\n

print("\n".join('{}. {} {}'.format(i, k, v) \
      for i, (k,v) in enumerate(shopping_list.items())))

This is one approach

shopping_list = {"eggs": "$2", "milk": "$3.50", "cereal": "$3"}
my_shopping_list = "\n".join(("{0} {1} {2}".format(i, v[0], v[1]) for i, v in enumerate(shopping_list.items(), 1)))
print(my_shopping_list)

Output:

1 eggs $2
2 milk $3.50
3 cereal $3

Make it readable using itertools.count .

from itertools import count

shopping_list = {"eggs": "$2", "milk": "$3.50", "cereal": "$3"}

c = count(1)
for k, v in shopping_list.items():
    print(f'{next(c)}. {k} {v}')

# 1. eggs $2
# 2. milk $3.50                                               
# 3. cereal $3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM