-1

I am trying to insert another key:value list of the data while print/storing in another result. Here is what I did till now:

>>> data = list()
>>> data.append({'data':'a','name':'alpha'})
>>> data.append({'data':'b','name':'beta'})
>>> data.append({'data':'c','name':'charlie'})
>>> data
[{'data': 'a', 'name': 'alpha'}, {'data': 'b', 'name': 'beta'}, {'data': 'c', 'name': 'charlie'}]
>>> names = []
>>> count = 0
>>> for i in data:
...     names.append(data[count]['name'])
...     count = count + 1
...
>>> names
['alpha', 'beta', 'charlie']
>>> txt = 'alpha'
>>> res = process.extract(txt,names)
>>> res
[('alpha', 100), ('charlie', 33), ('beta', 22)]
>>> for name, score in res:
...     print(data[names.index(name)])
...
{'data': 'a', 'name': 'alpha'}
{'data': 'c', 'name': 'charlie'}
{'data': 'b', 'name': 'beta'}
>>> for name, score in res:
...     print(data[names.index(name)]['score'] = score)
...
  File "<stdin>", line 2
SyntaxError: keyword can't be an expression

Kindly, let me know what I need to do, do that I get the result with added key:value. I am trying to get the output like this:

{'data': 'a', 'name': 'alpha', 'score': 100}
{'data': 'c', 'name': 'charlie', 'score': 33}
{'data': 'b', 'name': 'beta', 'score': 22}
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139

2 Answers2

2

In Python, assignment (here data[names.index(name)]['score'] = score) is a statement, so you cannot use it where an expression is expected. You have to first do the assignment, then print the result, ie replace this:

for name, score in res:
    print(data[names.index(name)]['score'] = score)

with:

for name, score in res:
    index = names.index(name)
    data[index]['score'] = score
    print data[index]

As a side note:

names = []
count = 0
for i in data:
    names.append(data[count]['name'])
    count = count + 1

is an incredibly complicated way to write:

names = [item["name"] for item in data]
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

Replace

for name, score in res:
    print(data[names.index(name)]['score'] = score)

with

for name, score in res:
    for d in data:
        if d['name']==name:
            d['score'] = score

Though it might be a better approach to use classes.

Joe
  • 6,758
  • 2
  • 26
  • 47