Hello,
newbie question again.
Let's say i have a list of nested dictionaries.
a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}]
What i want is to move a singularis entry of each duplicate where value1, value3 and value4 matches. The result should be looking like this:
b = [{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}]
The orginal list, a, should remain in it's orginal state.
From stackoverflow
-
There was a similar question on this recently. Try this entry.
In fact, you asked that question: "Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries."
It sounds like the same thing, right?
Edit: liberally stealing Alex's code, it looks something like this:
import itertools import pprint import operator alpha, charlie, norway, england = range(4) a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha}, {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}] getvals = operator.itemgetter('value1', 'value3', 'value4') a.sort(key=getvals) b = [g.next() for _, g in itertools.groupby(a, getvals)] pprint.pprint(b)
And the result is:
[{'value1': 1234, 'value2': 23423423421L, 'value3': 2, 'value4': 1}, {'value1': 1398, 'value2': 23423412221L, 'value3': 3, 'value4': 0}]
Jonas : Yes :) stupid of me.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.