Yoga Yudistira Yoga Yudistira - 1 year ago 88
Python Question

Get right data from dict inside list

I'm trying to get a video URL from tweet,

was taken from tweepy. Because twitter doesn't tell which one is the highest quality video I assume that I have to compare highest 'bitrate' and store the 'url' that corresponds with it. This is what I have.

Please bear with me, I'm new to this.

A = [{'content_type': 'application/x-mpegURL', 'url': ''},
{'bitrate': 832000, 'content_type': 'video/mp4', 'url': ''},
{'content_type': 'application/dash+xml', 'url': ''},
{'bitrate': 320000, 'content_type': 'video/mp4', 'url': ''}]

for i, val in enumerate(A):
if 'bitrate' in A[i]:
print(A[i]['bitrate'], A[i]['url'])

This code produces


How do I store the ['url'] that corresponds with highest ['bitrate'] into a variable?

Answer Source

If you want to get dictionary (or url) with the highest bitrate:

This compares the items of the list of dictionaries using bitrate key and returns dictionary with the highest bitrate.

max(A, key=lambda x:x['bitrate'])['url']

EDIT: According to your comment above, you can assign the url to variable of course.

variable = max(A, key=lambda x:x['bitrate'])['url']

EDIT1: According to your coment below - you believe right, you have to exclude such dictionaries from the list.

This excludes dictionaries without 'bitrate' key:

[d for d in A if d.has_key('bitrate')]

So you have to switch A to the line above so the result would be:

variable = max([d for d in A if d.has_key('bitrate')],key=lambda x:x['bitrate'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download