Yoga Yudistira Yoga Yudistira - 4 months ago 10
Python Question

Get right data from dict inside list

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

A
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': 'https://video.twimg.com/ext_tw_video/758995712280412672/pu/pl/X_6gAm0z8TBBbEAR.m3u8'},
{'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/758995754280412672/pu/vid/360x640/6nxKFKpdku-qAl__.mp4'},
{'content_type': 'application/dash+xml', 'url': 'https://video.twimg.com/ext_tw_video/758995715280412672/pu/pl/X_6gAm0z8TBBbEAR.mpd'},
{'bitrate': 320000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/758995715280412672/pu/vid/180x320/VqRF6IcnmsLxZIil.mp4'}]


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


This code produces

832000 https://video.twimg.com/ext_tw_video/758996713280412672/pu/vid/360x640/6nxKFKpdku-qAl__.mp4
320000 https://video.twimg.com/ext_tw_video/758997716280412672/pu/vid/180x320/VqRF6IcnmsLxZIil.mp4


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

Answer

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'])
Comments