0

How do I create p below?

Is this a list comprehension & .map() problem?

pr = [{"pr":"DEV"}, {"pr":"STEVE"}]

spr = "what"

p = [{"pr":"DEV", "spr":"what"}, {"pr":"STEVE", "spr":"what"}]

Steve
  • 905
  • 1
  • 8
  • 32
  • Does this answer your question? [Python Dictionary Comprehension](https://stackoverflow.com/questions/14507591/python-dictionary-comprehension) – Chayim Friedman Jan 13 '21 at 21:49
  • First of all, why do you want to create such a wastefull and complex data structure? I suggest implementing a class which has the "spr" and the list of "pr". Also, LPT: use better variable names, you will sometimes read code you wrote a long time ago. – zvone Jan 13 '21 at 21:57

2 Answers2

1

Given an arbitrary list of pr values, you can use

p = [{"pr": k, "spr": spr} for k in pr]

To handle the edit,

p = [dict(**x, spr=spr) for x in pr]
# In Python 3.9, 
# p = [x | {"spr": spr} for x in pr]  
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I'm sorry man. Maybe I couldn't see the forest for the trees. You cannot believe my how far flung my work got before I posted this. – Steve Jan 13 '21 at 21:50
  • To make this more interesting I edited my OP. Notice the difference in `pr`; list of a object. – Steve Jan 13 '21 at 21:55
1

Merge the dictionaries inside the list comprehension:

pr = [{"pr":"DEV"}, {"pr":"STEVE"}]
spr = "what"
p = [{**x, **{'spr': spr}} for x in pr]
print(p)
# [{'pr': 'DEV', 'spr': 'what'}, {'pr': 'STEVE', 'spr': 'what'}]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • I couldn't recognize this a dict merge problem. But is certainly is one if you create dict out of `spr` on the fly. – Steve Jan 13 '21 at 22:09