Home  >  Q&A  >  body text

Python newbie asked about for...in... traversal

code show as below:

# -*- coding:gb2312 -*-
infor = [{"name":"laowang","age":18},{"name":"laoli","age":20},{"name":"laotie","age":40},{"name":"wutianlong","age":29}]


for temp in infor:
    for temp2 in temp.key():
        print(temp2)

The running results are as follows:

My question:
I don’t know what the problem is with this code? I have 4 dictionaries in a list. I want to traverse the list once, then traverse the name key of the dictionary again in the traversal result, and then print the value of the name key. Why can't it be printed?

代言代言2685 days ago879

reply all(3)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-13 09:26:51

    keys

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-13 09:26:51

    1. First of all, it is keys, not key
    2. Secondly, for can traverse the dictionary directly without calling kes()

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-13 09:26:51

    The first floor is highlighted. Keys are the attributes of dict. The error "Dictionary object does not have an attribute called 'key'" has already explained the problem. At this time, you can find the answer by checking the dict index in the Python documentation.

    reply
    0
  • Cancelreply