myDict = results(results)
print("Subscribers: " + myDict['items'][0]['statistics']['subscriberCount'])
我试图将结果存储为变量,然后用于仅显示输出的某个部分。
如果我写
results_print(results)
它打印正确但我无法出于某种原因将其存储为变量。
这是结果的内容:
{'pageInfo': {'resultsPerPage': 1, 'totalResults': 1}, 'items': [{'snippet': {'publishedAt': '2013-10-20T10:33:50.000Z', 'country': 'SE', 'localized': {'description': 'Trap Town, the best trap music out there.\n\nSubmissions: traptownsubmit@gmail.com', 'title': 'Trap Town'}, 'customUrl': 'traptownmusic', 'title': 'Trap Town', 'description': 'Trap Town, the best trap music out there.\n\nSubmissions: traptownsubmit@gmail.com', 'thumbnails': {'default': {'url': 'https://yt3.ggpht.com/-4E1iRrrd_c8/AAAAAAAAAAI/AAAAAAAAAAA/cJeykUlKy8s/s88-c-k-no-mo-rj-c0xffffff/photo.jpg'}, 'medium': {'url': 'https://yt3.ggpht.com/-4E1iRrrd_c8/AAAAAAAAAAI/AAAAAAAAAAA/cJeykUlKy8s/s240-c-k-no-mo-rj-c0xffffff/photo.jpg'}, 'high': {'url': 'https://yt3.ggpht.com/-4E1iRrrd_c8/AAAAAAAAAAI/AAAAAAAAAAA/cJeykUlKy8s/s240-c-k-no-mo-rj-c0xffffff/photo.jpg'}}}, 'statistics': {'videoCount': '354', 'commentCount': '0', 'hiddenSubscriberCount': False, 'viewCount': '1417504', 'subscriberCount': '12178'}, 'kind': 'youtube#channel', 'id': 'UCipITl9sF0qOhCyx9CyoPGA', 'etag': '"m2yskBQFythfE4irbTIeOgYYfBU/dy7xO_v59s1GVGj_ZJRXB_3rico"', 'contentDetails': {'relatedPlaylists': {'watchHistory': 'HL', 'uploads': 'UUipITl9sF0qOhCyx9CyoPGA', 'favorites': 'FLipITl9sF0qOhCyx9CyoPGA', 'watchLater': 'WL', 'likes': 'LLipITl9sF0qOhCyx9CyoPGA'}}}], 'kind': 'youtube#channelListResponse', 'etag': '"m2yskBQFythfE4irbTIeOgYYfBU/p-3fTLLWdWeBZO-Q-vqxfEbNIhw"'}
这是功能吗?
def channels_list_by_id(service, **kwargs):
kwargs = remove_empty_kwargs(**kwargs) # See full sample for function
results = service.channels().list(
**kwargs
).execute()
def print_results(results):
print(results)
答案 0 :(得分:1)
我猜你是想这样做的:
def get_subscriber_count(results):
return results['items'][0]['statistics']['subscriberCount']
results = channels_list_by_id(service, **kwargs)
print("Subscribers:", get_subscribers_count(results))
如果您尝试将匿名函数分配给变量,就像使用Javascript这样的语言一样,您可以尝试这样做:
get_subscribers_count = lambda r: r['items'][0]['statistics']['subscriberCount']
但在Python中,这仅限于单行。
如果results
是字符串,则需要先解析它才能访问密钥:
import json
def get_subscriber_count(results):
parsed_results = json.loads(results)
return parsed_results['items'][0]['statistics']['subscriberCount']
# or
get_subscriber_count = lambda r: json.loads(r)['items'][0]['statistics']['subscriberCount']
[更新]
channels_list_by_id
的一个问题是它缺少return
语句,因此返回None
。与许多其他语言不同,Python不返回最后一个语句的值,您必须明确返回:
def channels_list_by_id(service, **kwargs):
kwargs = remove_empty_kwargs(**kwargs) # See full sample for function
return service.channels().list(
**kwargs
).execute()