如何在python中打印字典? (在单独的行中逐一打印)

时间:2019-04-11 00:08:15

标签: python pycharm

我想用python打印字典。

menu = {
        1: ("Single Red Roses", 29),
        2: ("Burst of Spring Posy", 59),
        3: ("Super Grade Red Roses", 69),
        4: ("Lemon Gelato Roses", 79),
        5: ("Market Fresh Pin Lily", 79),
        6: ("Summer Daisy Gerbera", 79),
        7: ("Bag of Garden Roses", 89),
        8: ("Blue Lime Spring Rosy", 89),
        9: ("Hot Pink Roses", 89),
        10: ("Class White Roses", 99),
        11: ("Fresh Lime", 109),
        12: ("Boxed Red Roses", 129),
        13: ("Tropical Rain-forest Bouquet", 149),
    }

这是我的代码,我不知道该怎么做,因为我非常感谢您的帮助:)

编辑:如何制作它,以便它一张一张地打印每个列表。

2 个答案:

答案 0 :(得分:2)

您导致使用内置的print()函数

print(menu)
  

{1:('Single Red Roses',29),2:(''Burst of Spring Posy',59),3 :('Super Grade Red Roses',69),4:('Lemon Gelato Roses' ,79),5 :(“ Market Fresh Pin Lily”,79),6 :(“ Summer Daisy Gerbera”,79),7 :(“ Bag of Garden Roses”,89),8 :(“ Blue Lime Spring Rosy” ',89),9:('粉红玫瑰',89),10:('白玫瑰类',99),11:('鲜青柠',109),12:('盒装红玫瑰',129 ),13 :(“热带雨林花束”,149)}

对于格式化输出到控制台,可以使用pprint模块

import pprint

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(menu)

给你

{   1: ('Single Red Roses', 29),
    2: ('Burst of Spring Posy', 59),
    3: ('Super Grade Red Roses', 69),
    4: ('Lemon Gelato Roses', 79),
    5: ('Market Fresh Pin Lily', 79),
    6: ('Summer Daisy Gerbera', 79),
    7: ('Bag of Garden Roses', 89),
    8: ('Blue Lime Spring Rosy', 89),
    9: ('Hot Pink Roses', 89),
    10: ('Class White Roses', 99),
    11: ('Fresh Lime', 109),
    12: ('Boxed Red Roses', 129),
    13: ('Tropical Rain-forest Bouquet', 149)}

答案 1 :(得分:2)

for key,val in menu.items():
    print(key + ": " + val)

输出:

    1: ("Single Red Roses", 29),
    2: ("Burst of Spring Posy", 59),
    3: ("Super Grade Red Roses", 69),
    4: ("Lemon Gelato Roses", 79),
    5: ("Market Fresh Pin Lily", 79),
    6: ("Summer Daisy Gerbera", 79),
    7: ("Bag of Garden Roses", 89),
    8: ("Blue Lime Spring Rosy", 89),
    9: ("Hot Pink Roses", 89),
    10: ("Class White Roses", 99),
    11: ("Fresh Lime", 109),
    12: ("Boxed Red Roses", 129),
    13: ("Tropical Rain-forest Bouquet", 149),