繁体   English   中英

python:从字典中获取值并将其作为键插入到另一个字典中

[英]python: getting value from a dictionary and inserting it into another dictionary as key

我想将其打印出来,其中每个键代表公司名称,值代表启动的视频数量,例如以下示例:{“ Grab”:1,“ Uber”:3}

但我可以获得正确的值。 请指教。 谢谢!

video_ads = [
{"title": "Healthy Living", "company": "Uber", "views": 15934, "created_days_ago": 302, "bounce_rate": 0.17},
{"title": "Get a ride, anytime anywhere", "company": "Uber", "views": 923834, "created_days_ago": 289, "bounce_rate": 0.11},
{"title": "Send money to your friends with GrabPay", "company": "Grab", "views": 23466, "created_days_ago": 276, "bounce_rate": 0.08},
{"title": "Ubereats now delivers nationwide", "company": "Uber", "views": 1337, "created_days_ago": 270, "bounce_rate": 0.04}
]


industry_data = {}
videos_count = 0

for key in video_ads:
    print(key["company"])
    company = key["company"]

if company in industry_data:
    videos_count += 1

else:
    industry_data[company] = videos_count
    videos_count += 1

print(industry_data)

使用collections.Counter

from collections import Counter

video_ads = [
{"title": "Healthy Living", "company": "Uber", "views": 15934, "created_days_ago": 302, "bounce_rate": 0.17},
{"title": "Get a ride, anytime anywhere", "company": "Uber", "views": 923834, "created_days_ago": 289, "bounce_rate": 0.11},
{"title": "Send money to your friends with GrabPay", "company": "Grab", "views": 23466, "created_days_ago": 276, "bounce_rate": 0.08},
{"title": "Ubereats now delivers nationwide", "company": "Uber", "views": 1337, "created_days_ago": 270, "bounce_rate": 0.04}
]

c = Counter(x['company'] for x in video_ads)

print(c)
# Counter({'Uber': 3, 'Grab': 1})

问题在于您积累数据的方式。 应该在for循环中完成。 您不需要额外的video_count 只需将它们总结在industry_data如下所示:

industry_data = {}

for key in video_ads:
    company = key["company"]

    if company in industry_data:
        industry_data[company] += 1
    else:
        industry_data[company] = 1

print(industry_data)
# {'Uber': 3, 'Grab': 1}
result_dict = {}
for k in video_ads:
    try:
        result_dict[k['company']] += 1
    except KeyError:
        result_dict[k['company']] = 1

print (result_dict)
#{'Uber': 3, 'Grab': 1}

您几乎正确了。 if循环应在for循环内,并进行一些较小的修改,如下所示:

industry_data = {}
videos_count = 0

for key in video_ads:
    print(key["company"])
    company = key["company"]
    if company not in industry_data:
        industry_data[company] = 1
    else:
        industry_data[company] += 1

print(industry_data)

暂无
暂无

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

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