简体   繁体   中英

Python:Accessing a particular dictionary present in a list of dictionary

list1:[
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5},
    {"name": "Pam", "age": 7}
       ]

I want to access the second dictionary. I have tried with giving key.

next(item for item in dicts if item["name"] == "Mark")

But i dont have the key. I want to do some operation with the help of second dictionary. Can any one help?' Here i want to access each dictionary without indices & doing some operation with each dictionary & moving towards next dictionary to do operation for next dictionary & so on. Is there any way?

Since list1 is a list of dictionary so try to access dictionaries using list indices ( for this case 0-2)-

 >>>print list1[1]["name"]
>>>Mark
>>>lsit1[1]["name"] = 'Blah'
>>>lsit1
>>>[{'age': 10, 'name': 'Tom'}, {'age': 5, 'name': 'Blah'}, {'age': 7, 'name': 'Pam'}]
>>>del lsit1[1]['name'] #Delete a key
>>>lsit1
>>>[{'age': 10, 'name': 'Tom'}, {'age': 5}, {'age': 7, 'name': 'Pam'}]
>>>lsit1[1]['new_name']='Test'  #Add a key
>>>lsit1
>>>[{'age': 10, 'name': 'Tom'}, {'new_name': 'Test', 'age': 5}, {'age': 7, 'name': 'Pam'}]

EDIT-

It looks your data is json compatiable then try json module-

>>>import json
>>>#use json.loads and dumps to format data as below
>>>data =  {'list1':[{"name":"Tom","age":10},{"name":"Mark","age":5},{"name":"Pam","age":7}]}
>>>data['list1'][1]
>>>{'age': 5, 'name': 'Mark'}

Simply use indexing .

In [134]: list1[1]['name']
Out[134]: 'Mark'

For second dict .

In [137]: l[1]
Out[137]: {'age': 5, 'name': 'Mark'}

for solve through for loop and for accessing the second item in list .

In [139]: for k, v in enumerate(l):
    if k==1:
        print v
   .....:         
{'age': 5, 'name': 'Mark'}

您可以使用此:

list1[1]["name"]="some thing"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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