简体   繁体   English

如何在不循环的情况下打印项目名称?

[英]how do i print the names of the items without looping?

在此处输入图片说明

This is the code:这是代码:

itemDict = {"Laptop" : 3499.0, "Keyboard" : 10.5, "Harddisk" : 159.3, "Mouse" : 8.9}

print("Item Listing")

print("---------------------")

def displayItem(itemDict):
    i = list(itemDict.values())

    return i
def names(itemDict):
    j = list(itemDict.keys())

    return j
for names in names(itemDict):
    for values in displayItem(itemDict):
        print(names + " - $" + str(values))

Or a one-liner:或单线:

d = {"Laptop" : 3499.0, "Keyboard" : 10.5, "Harddisk" : 159.3, "Mouse" : 8.9}
print('\n'.join(' - $'.join(map(str,i)) for i in zip(sorted(list(d.keys())*len(d),key=list(d.keys()).index),sorted(list(d.values())*len(d),key=list(d.values()).index))))

You can make it a bit simpler if that is what you are looking for:如果这是您要查找的内容,则可以使它更简单一些:

for i in itemsDict:
    print i, itemsDict[i]

that will print the key:value pair这将打印键:值对

For a dynamically changing Dict I don't think there is another way to print all the values other than iterating through it.对于动态变化的 Dict,我认为除了迭代之外,没有其他方法可以打印所有值。

Hope that helps :)希望有帮助:)

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

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