-2

I have a dictionary and a list. I want to add a new key to the dictionary so that the value of each of them is equal to one of the array elements. I have explained more about this in the example below

my dictionary

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]

my list

['a','b','c']

What I want:

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1 , 'content' ='a'},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2,  'content' ='b'},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3,  'content' ='c'}
]
user12217822
  • 292
  • 1
  • 5
  • 16

2 Answers2

1

You can use zip to pair up the dictionaries withe the content strings and set the 'content' key for each:

dicList = [{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]
contents = ['a','b','c']
for d,c in zip(dicList,contents):
    d['content'] = c

print(dicList)

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1, 'content': 'a'}, 
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2, 'content': 'b'}, 
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3, 'content': 'c'}]

Or, if you want the result in a new list, you can use a list comprehension to build augmented dictionaries:

dicList2 = [{**d, 'content':c} for d,c in zip(dicList,contents)]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Zip and assign:

for d, d['content'] in zip(dicts, contents):
    pass

Demo (Try it online!):

import pprint

dicts = [{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]
contents = ['a','b','c']

for d, d['content'] in zip(dicts, contents):
    pass

pprint.pp(dicts)

Output:

[{'url': 'https://test.com/find/city-1',
  'tit': 'title1',
  'val': 1,
  'content': 'a'},
 {'url': 'https://test.com/find/city-2',
  'tit': 'title1',
  'val': 2,
  'content': 'b'},
 {'url': 'https://test.com/find/city-3',
  'tit': 'title1',
  'val': 3,
  'content': 'c'}]
no comment
  • 6,381
  • 4
  • 12
  • 30
  • Interesting implementiation! I never knew you could do that! +1 – Jab Oct 10 '21 at 23:55
  • @Jab Yeah, seems many people don't know. I've been doing it for a long time and have rarely ever seen anyone else doing it. [Some benefits](https://stackoverflow.com/a/69244531/16759116). – no comment Oct 11 '21 at 00:08