【问题标题】:Python: print dictionary keys and values individuallyPython:单独打印字典键和值
【发布时间】:2016-01-24 05:13:21
【问题描述】:

我想知道:如何从函数中的字典中单独打印键或值?

.txt 文件示例

 00000000;Pikachu Muchacho;region1
 11111111;SoSo good;region2
 22222222;Marshaw williams;region3
 33333333;larry Mikal Carter;region3

代码

test_file = open("test.txt", "r")
customer = {}
def dictionary():
    for line in test_file:
        entries = line.split(";")
        key = entries[0]
        values = entries[1]
        customer[key] = values

def test():
    print(customer)
    print(customer[key])

def main():
    dictionary()
    test()

main()

【问题讨论】:

  • customer.keys() 和 customer.values() 为您提供所有键和所有值
  • 我不是在投反对票,但这是我真诚的建议,您在提出此类问题之前要付出更多努力。
  • 我确实付出了努力。这就是我问的原因,因为我尝试了几种不同的方法,但我没有弄清楚。在你给出你的意见之前,先考虑一下。总的来说,我是语言和编码新手。

标签: python-3.x


【解决方案1】:

正如@jamesRH 所说,您可以使用customer.keys()customer.values()

test_file = open("test.txt", "r")
customer = {}
def dictionary():
    for line in test_file:
        entries = line.split(";")
        key = entries[0]
        values = entries[1]
        customer[key] = values

def test():
    # Print all the keys in customer
    print(customer.keys())

    # Print all the values in customer
    print(customer.values())

def main():
    dictionary()
    test()

main()

这给出了输出:

['00000000', '22222222', '33333333', '11111111']
['Pikachu Muchacho', 'Marshaw williams', 'larry Mikal Carter', 'SoSo good']

您的原始代码会导致错误,因为key 不在test() 的范围内。

【讨论】:

  • 谢谢。如果我想像列中一样垂直输出它们,只包含条目,而没有附加任何其他内容,该怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 2021-08-14
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 2023-01-03
相关资源
最近更新 更多