I'm using Python v3.10.4.
I have two lists of dictionaries that are the same length typically a few hundred lines long, I need to combine them. These lists they represent security indicators of compromise that need to be enriched and fed to a firewall:
uniq = [
{'uniq-name': '2022-06-26 14:21:25.298167'},
{'uniq-name': '2022-06-26 14:21:25.298204'}
]
iocvalue = [
{'value': '116.30.7.55'},
{'value': '31.215.70.187'}
]
I'd like to produce this arrangement:
summary = [{uniq-name:'2022-06-26 14:21:25.298167',
value:'116.30.7.55'}]
I've tried:
[{[val for val in uniq] [ val for val in iocvalue]}]
as well as several variations of **uniq, **iocvalue, but I couldn't get it working. What should I do?
CodePudding user response:
You can use a union operation between each pair of dictionaries using a list comprehension and zip()
. The syntax for the union operation depends on the Python version:
Python 3.9
[fst | snd for fst, snd in zip(uniq, iocvalue)]
Python <3.9:
[dict(**fst, **snd) for fst, snd in zip(uniq, iocvalue)]
(Note that the dict(**x, **y)
syntax is still supported in Python 3.9 , it's just that using |
instead is just more concise and readable.)
These output:
[
{'uniq-name': '2022-06-26 14:21:25.298167', 'value': '116.30.7.55'},
{'uniq-name': '2022-06-26 14:21:25.298204', 'value': '31.215.70.187'}
]
CodePudding user response:
Using a dictionary union operator (Python 3.9 ):
>>> [u | v for u, v in zip(uniq, iocvalue)]
[{'uniq-name': '2022-06-26 14:21:25.298167', 'value': '116.30.7.55'},
{'uniq-name': '2022-06-26 14:21:25.298204', 'value': '31.215.70.187'}]
For older Python versions:
>>> [{**u, **v} for u, v in zip(uniq, iocvalue)]
[{'uniq-name': '2022-06-26 14:21:25.298167', 'value': '116.30.7.55'},
{'uniq-name': '2022-06-26 14:21:25.298204', 'value': '31.215.70.187'}]
CodePudding user response:
I hope this can be usefull.
You need to zip both dict:
zipped = zip (uniq,iocvalue)
But zipped is now a 'zip object'
To access it, you can do:
print (*zipped)
Then you get this output:
({'uniq-name': '2022-06-26 14:21:25.298167'}, {'value': '116.30.7.55'}) ({'uniq-name': '2022-06-26 14:21:25.298204'}, {'value': '31.215.70.187'})
CodePudding user response:
`
summary = []
for i, j in zip(uniq, iocvalue):
i.update(j)
summary.append(i)
# Answer: [{'uniq-name': '2022-06-26 14:21:25.298167', 'value': '116.30.7.55'}, {'uniq-name': '2022-06-26 14:21:25.298204', 'value': '31.215.70.187'}]
`