简体   繁体   English

访问词典列表中的词典

[英]Accessing a dictionary within a list within a dictionary

user = code.chan["#example"]["Someuser"]
# user would look something like:
{
    'normal': True,
    'voiced': False,
    'op': False,
    'count': 24,
    'messages': [
        {
            'time': 1448847813,
            'message': "This is my mesage"
        },
        {
            'time': 1448847818,
            'message': "And this is another"
        }
    ]
}

I am trying to get put the items in 'message' into a list to check whether a string matches any of the items. 我正在尝试将“消息”中的项目放入列表中,以检查字符串是否与任何项目匹配。

Let me know if more information is needed. 让我知道是否需要更多信息。

I guess you want this: 我猜你想要这个:

print [i['message'] for i in user['messages']]

Or, 要么,

print map(lambda x:x['message'],user['messages'])

Output: 输出:

['This is my mesage', 'And this is another']

To print only the last item, you can use negative indexing. 要仅打印最后一项,可以使用负索引。 Just like below: 就像下面这样:

print [i['message'] for i in user['messages']][-1]

Output: 输出:

And this is another

You can do that like so: 您可以这样做:

for message in user['messages']:
    if some_string == message['message']:
        match = True

If you're looking to search through them you'd want to do something like; 如果您要搜索它们,您可能想要做类似的事情;

if any(search_string in i['message'] for i in user['messages']):
    print 'found your query'

Ok i am a bit confused by the question but if i imagined correctly here is my answer. 好的,我对这个问题有点困惑,但是如果我没有正确想象的话,这就是我的答案。

You have a list of lists and i suspect it is in json format so you need to access it like this 您有一个列表列表,我怀疑它是json格式,因此您需要像这样访问它

#fetch data 
r = requests.get(wherever_you_fetch_them)
s = r.content.decode()
json_resp = json.loads(s)

succ = json_resp['messages']['message']

and you can create a loop, but i cant help you more because i don't know any information about input data. 您可以创建一个循环,但是我不能为您提供更多帮助,因为我不知道有关输入数据的任何信息。

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

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