简体   繁体   English

如何使用PYTHON访问保存为JSON中的键列表的所有词典的第一个键的值

[英]How to access the value of 1st key of all the dictionaries saved as a list for a key in JSON using PYTHON

I have the JSON which looks like this:- 我有看起来像这样的JSON:-

{
        "name": "PT",
        "batservers": [
            {"name": "bat1", "qmchannel": "abcd", "mount": "efgh"},
            {"name": "bat2", "qmchannel": "abcd", "mount": "efgh"},
            {"name": "bat3", "qmchannel": "abcd", "mount": "efgh"},
        ]
    }

I want to retrieve the value of "name" present in all the dictionary and save it in a list variable ie ["bat1","bat2","bat3"] 我想检索所有字典中存在的“名称”的值并将其保存在列表变量中,例如[“ bat1”,“ bat2”,“ bat3”]

I tried something like this:- 我尝试过这样的事情:

batsList = env["batservers"][0:]["name"]

but it displays the below error:- 但显示以下错误:-

TypeError: list indices must be integers or slices, not str

I know I can do this using a loop but can someone please help me to do using in a single line code way which I am trying above? 我知道我可以使用循环来做到这一点,但是有人可以帮助我以上面尝试的单行代码方式使用吗?

Thanks, SUYASH GUPTA. 谢谢SUYASH GUPTA。

You can't do it without a loop. 你不能没有循环。 But the loop can be a list comprehension: 但是循环可以是列表理解:

batsList = [b['name'] for b in env["batservers"]

How about saving the list as: 如何将列表另存为:

list_of_names = [x[name] for x in env["batservers"]] list_of_names = [对于x在env [“ batservers”]中的x [name]]

Try this: 尝试这个:

[b['name'] for b in env['batservers']]

Or this: 或这个:

map(lambda b: b['name'], env['batservers'])

[0:] doesn't do much for you: it returns the same array of dictionaries. [0:]对您没有多大帮助:它返回相同的字典数组。

env["batservers"][0:] returns a list, and you can't access directly the values of the dicts in the list. env["batservers"][0:]返回一个列表,您不能直接访问列表中env["batservers"][0:]的值。

You can use a list comprehension: 您可以使用列表理解:

names = [elem["name"] for elem in env["batservers"]]

This is a basic solution using a for loop to iterate over the sub dictionary and appending to the empty list res . 这是使用for循环迭代子词典并追加到空列表 res的基本解决方案。

res = []
for item in env["batservers"]:
  res.append(item["name"])

print (res) #=> ['bat1', 'bat2', 'bat3']

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

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