如何从dicts列表中检索项目

时间:2018-03-31 03:49:09

标签: python list dictionary data-structures

我有这个文件结构:

server_id = 1
message = "hello bob, how are you?"
a = [
        {
            "server_id": 1,
            "contents:   [
                {
                    "word": "hello",
                    "reaction: "greetings"
                }
            ]
        }
    ]

我如何正确地导航这个结构以获得"问候"如果这个词"你好"在服务器1的消息中使用?

2 个答案:

答案 0 :(得分:0)

server_id = 1
message = "hello bob, how are you?"
a = [
        {
            "server_id": 1,
            "contents":   [
                {
                    "word": "hello",
                    "reaction": "greetings"
                }
            ]
        }
    ]

for msg in a :
    for contentKey in msg.keys():
            if 'contents' == contentKey:
                if msg[contentKey][0]['word'] in message : #check if the word is in message only then show reaction
                    print("reaction is  :" + msg[contentKey][0]['reaction'])

以下是您如何检索消息

答案 1 :(得分:0)

If your result from the server is always same format you can try this approach:

if a[0]['contents'][0]['word']=='hello':
    print(a[0]['contents'][0]['reaction'])

or

format=a[0]['contents'][0]

if format['word']=='hello':
    print(format['reaction'])

output:

greetings