2

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

3 Answers 3

4

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}]
Sign up to request clarification or add additional context in comments.

5 Comments

i think you need names[d]
@JoranBeasley pardon?
d is just the key isnt it? maybe not i guess not since it actually looks like you ran it
@JoranBeasley d is a dict from the list of dicts names.
lol its clearly too late i need to go to bed :P ... great answer (I gave you +1 earlier)
2

Without list comprehension.

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

print(names)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.