简体   繁体   English

Python:访问词典列表中存在的特定词典

[英]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)- 由于list1dictionarylist ,因此请尝试使用列表索引(在这种情况下为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- 看起来您的数据是json可兼容的,然后尝试json模块-

>>>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 . 只需使用indexing

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

For second dict . 第二个dict

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

for solve through for loop and for accessing the second item in list . 用于解决for循环和访问list的第二个项。

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

您可以使用此:

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

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

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