简体   繁体   English

我希望能够打印字典中键的名称,然后是描述、值和数量

[英]I want to to be able to print the name of the keys in the dictionary then the description, value and quantity

what i want the output to look like is this:我想要的输出是这样的:

IM. Iced Milo (S$1.5) Qty:  2 
HM. Hot Milo (S$1.2) Qty:  20 
IC. Iced Coffee (S$1.5) Qty:  2 
HC. Hot Coffee (S$1.2) Qty:  0 
1P. 100 Plus (S$1.1) Qty:  50 
CC. Coca Cola (S$1.3) Qty:  50 

Instead my output is like this:相反,我的输出是这样的:

None Iced Milo (S$1.5) Qty:  2 

None Hot Milo (S$1.2) Qty:  20 

None Iced Coffee (S$1.5) Qty:  2 

None Hot Coffee (S$1.2) Qty:  0 

None 100 Plus (S$1.1) Qty:  50 

None Coca Cola (S$1.3) Qty:  50 

Here is my code:这是我的代码:

nested_dictionary = {
    "IM.": {
        "description": "Iced Milo",
        "price": "(S$1.5)",
        "quantity": "%d" % (int(IMquantity)),
    },
    "HM.": {
        "description": "Hot Milo",
        "price": "(S$1.2)",
        "quantity": "%d" % (int(HMquantiy)),
    },
    "IC.": {
        "description": "Iced Coffee",
        "price": "(S$1.5)",
        "quantity": "%d" % (int(ICquantity)),
    },
    "HC.": {
        "description": "Hot Coffee",
        "price": "(S$1.2)",
        "quantity": "%d" % (int(pprint)),
    },
    "1P.": {
        "description": "100 Plus",
        "price": "(S$1.1)",
        "quantity": "%d" % (int(onePquantity)),
    },
    "CC.": {
        "description": "Coca Cola",
        "price": "(S$1.3)",
        "quantity": "%d" % (int(CCquantity)),
    },
}
for x in nested_dictionary:
    print(nested_dictionary, end=" ")
    print(nested_dictionary[x]["description"], end=" ")
    print(nested_dictionary[x]["price"], end=" ")
    if nested_dictionary[x]["quantity"] == 0:
        print("Qty: ***out of stock***\n")
    else:
        print("Qty: ", nested_dictionary[x]["quantity"], "\n")

Here's a reformulation of your code to use a list of products (if you wanted, turning that into a dict-of-dicts is a single dictionary comprehension away: nested_dictionary = {p["code"]: p for p in products} .这是您的代码的重新编写以使用产品列表(如果您愿意,将其转换为 dict-of-dicts 是一个单独的字典理解: nested_dictionary = {p["code"]: p for p in products}

In addition, we're using .format_map() , which accepts a mapping (eg a dictionary) and formats a string using the given format string and data in that dict.另外,我们使用.format_map()它接受一个映射(例如字典) 格式的字符串使用在字典给定格式的字符串和数据。

products = [
    {
        "code": "IM",
        "description": "Iced Milo",
        "price": 1.5,
        "quantity": 2,
    },
    {
        "code": "HM",
        "description": "Hot Milo",
        "price": 1.2,
        "quantity": 20,
    },
    {
        "code": "IC",
        "description": "Iced Coffee",
        "price": 1.5,
        "quantity": 2,
    },
    {
        "code": "HC",
        "description": "Hot Coffee",
        "price": 1.2,
        "quantity": 0,
    },
    {
        "code": "1P",
        "description": "100 Plus",
        "price": 1.1,
        "quantity": 50,
    },
    {
        "code": "CC",
        "description": "Coca Cola",
        "price": 1.3,
        "quantity": 50,
    },
]

for product in products:
    line = "{code}. {description} (S${price:.2f}) Qty: {quantity}".format_map(product)
    print(line)

The output is输出是

IM. Iced Milo (S$1.50) Qty: 2
HM. Hot Milo (S$1.20) Qty: 20
IC. Iced Coffee (S$1.50) Qty: 2
HC. Hot Coffee (S$1.20) Qty: 0
1P. 100 Plus (S$1.10) Qty: 50
CC. Coca Cola (S$1.30) Qty: 50
for x in nested_dictionary:
    print(x, nested_dictionary[x]['description'], nested_dictionary[x]['price'], 'Qty:', end=' ')
    if int(nested_dictionary[x]['quantity']) == 0:
            print("***out of stock***")
    else:
        print(nested_dictionary[x]['quantity'])

You need to use the dict.items() to iterate over the dictionary Here is the code您需要使用 dict.items() 来遍历字典这里是代码

for (key,value) in nested_dictionary.items():
    print(key,end=' ')
    print(value['description'],end=' ')
    print(value['price'],end=' ')
    if (value['quantity'] == 0):
        print("Qty: ***out of stock***\n")
    else:
        print(value['quantity']), "\n"

要打印键的名称,您必须在 for 循环中添加以下内容:

print(x, end=" ")

Trying to change your code as little as possible, here is the solution I got.尝试尽可能少地更改您的代码,这是我得到的解决方案。

  1. I changed the first print line to print the value of 'x' instead of trying to index into the dictionary again.我更改了第一个打印行以打印 'x' 的值,而不是再次尝试索引到字典中。
  2. I changed the way the quantity key was stored, as instead of using the % operators, you can directly store the value as ints.我改变了数量键的存储方式,因为您可以直接将值存储为整数,而不是使用 % 运算符。 This is the final code I got:这是我得到的最终代码:
nested_dictionary = {'IM.': {'description': 'Iced Milo', 'price': '(S$1.5)', 'quantity': int(IMquantity)},
                             'HM.': {'description': 'Hot Milo', 'price': '(S$1.2)', 'quantity': int(HMquantiy)},
                             'IC.': {'description': 'Iced Coffee', 'price': '(S$1.5)', 'quantity': int(ICquantity)},
                             'HC.': {'description': 'Hot Coffee', 'price': '(S$1.2)', 'quantity': int(pprint)},
                             '1P.': {'description': '100 Plus', 'price': '(S$1.1)', 'quantity': int(onePquantity)},
                             'CC.': {'description': 'Coca Cola', 'price': '(S$1.3)', 'quantity': int(CCquantity)}
for x in nested_dictionary:
    print(x, end=' ')
    print(nested_dictionary[x]['description'], end=' ')
    print(nested_dictionary[x]['price'], end=' ')
    if nested_dictionary[x]['quantity'] == 0:
            print("Qty: ***out of stock***\n")
    else:
            print("Qty: ", nested_dictionary[x]['quantity'], "\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字典和输入:如果 `input` 包含我要打印的任何键值 - Dictionary and Input: if the `input` contains any of the keys I want to print the value 我想从课堂上打印字典中的键 - I want to print keys in a dictionary from class 是否可以选择要在 Python 中打印的字典键? - Is it possible to choose which dictionary keys I want to print in Python? 我想打印我传递给 Django 中的 HTML 页面的字典的键和值 - I want to print both, keys and values of dictionary which I pass in render to a HTML page in Django 我在 pandas dataframe 列中有字典作为值。 我想将键列和值作为列值 - I have dictionary as value in pandas dataframe columns. I want to make the keys columns and values as column value 我无法获取字典键 - I am not able to get dictionary keys 打印不带字典名称的字典键? 如何/为什么? - Print Dictionary Keys without Dictionary Name? How/why? 我想在字典的键内对整数进行排序 - I want to sort integers within the keys of a dictionary 我在字典中有多个键想要指向相同的值我能做什么 - I have Multiple keys in the dictionary want to point to the same value what can I do 如何创建字典外的列表,其名称与字典键相同,并且大小与该键的值相同? - How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM