简体   繁体   English

Python 3-从字典打印特定列表项

[英]Python 3 - Print Specific List Item from Dictionary

I have a dictionary with lists attached to the keys with multiple values inside each list. 我有一本字典,其中的键列表附加在每个列表中有多个值的键上。 I'm trying to pull a specific item from the lists of each key. 我正在尝试从每个键的列表中拉出特定项目。 I assumed I could do the following; 我以为我可以做到以下几点;

for entries in myDictionary:
    print("Customer :" + entries[1])
    print("Sales Rep:" + entries[2])
    print("Item: " + entries[3])

Though that only prints the second, third, and fourth characters of what I assume to be the key itself - it could also be the first list item as I also have the key as the first item within the lists, but I'm going to assume it's the former. 尽管那只会打印我认为是键本身的第二,第三和第四个字符-它也可能是第一个列表项,因为我也将键作为列表中的第一项,但是我要假设是前者。

I've read about the following, but I'm unsure how to apply it to my case of wanting to print a specific item from the list. 我已经阅读了以下内容,但是我不确定如何将其应用于希望从列表中打印特定项目的情况。 I believe these would print out the entire list per key; 我相信这些可以打印出每个键的整个列表;

for key, value in my_dict.iteritems():
    print key, value
for key in my_dict.iterkeys():
    print key
for value in my_dict.itervalues():
    print value

Cheers. 干杯。

Iterating over the dictionary gives you keys ; 遍历字典给你 ; you can always use that key to access the value: 您可以随时使用该键来访问值:

for key in myDictionary:
    entries = myDictionary[key]
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

Using dict.values() (or dict.itervalues() or dict.viewvalues() when using Python 2) gives you access to the values instead, which you can then index: 在使用Python 2时,使用dict.itervalues() dict.values() (或dict.itervalues()dict.viewvalues() )可以访问值,然后可以对其进行索引:

for entries in myDictionary.values():
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

or you can have both the keys and the values with dict.items() ( dict.iteritems() , dict.viewitems() ): 或者您也可以使用dict.items()dict.iteritems()dict.viewitems() )同时拥有键和值:

for key, entries in myDictionary.items():
    print("Details for:", key)
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

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

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