简体   繁体   中英

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

#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.

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