简体   繁体   中英

how to add list values to existing dictionary in python

Im trying to add each values of score to the dict names i,e score[0] to names[0] and so on...

names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]

Output should be like this

names=[{'id': 1, 'name': 'laptop','score':0.98}, {'id': 2, 'name': 'box','score':0.81}, {'id': 3, 'name': 'printer','score':0.78}]

How to achieve this? thanks in advance

I'd do it with a comprehension like this:

>>> [{**d, 'score':s} for d, s in zip(names, score)]
[{'id': 1, 'name': 'laptop', 'score': 0.9894376397132874}, {'id': 2, 'name': 'box', 'score': 0.819094657897949}, {'id': 3, 'name': 'printer', 'score': 0.78116521835327}]

Without list comprehension.

for i, name in enumerate(names):
    name['score'] = score[i]

print(names)

This is an easy-to-understand solution. From your example, I understand you don't want to round up the numbers but still want to cut them.

import math

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]
n = len(score)
for i in range(n):
    names[i]["score"] = truncate(score[i], 2)

print(names)

If you do want to round up the numbers:

names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]
n = len(score)
for i in range(n):
    names[i]["score"] = round(score[i], 2)

print(names)

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