如何一起使用Python里for循环和dictionary字典

2024-11-11 08:39:30

1、新建一个空白的PYTHON文档。

如何一起使用Python里for循环和dictionary字典

2、先定义一个字典的内容,并且打印看看有没有错误。person = { "Peter": "funny", "Jence": "Super", "Alice": "Crazy", "Ben": "Smart",}print(person)

如何一起使用Python里for循环和dictionary字典

3、如果直接运用FOR循环,那么只会把关键词显示出来,里面的值不会显示。for details in person: print(details)

如何一起使用Python里for循环和dictionary字典

4、在字典后加.values()可以显示值,但是不显示关键词。for details in person.values(): print(details)

如何一起使用Python里for循环和dictionary字典

5、在字典后加.items()可以同时显示关键词和值。for details in person.items(): print(details)

如何一起使用Python里for循环和dictionary字典

6、最好的方法还是加上key,value这样可以显示更多东西。for key,value in person.items(): print("Person: " + str(ke)y + " is " + str(value))

如何一起使用Python里for循环和dictionary字典

7、如果只是字符串就可以单单这样显示即可。for key,value in person.items(): print("Person: " + key + " is " + value)

如何一起使用Python里for循环和dictionary字典
猜你喜欢