How to append and uniqify a tuple
d1 = ({'x':1, 'y':2}, {'x':3, 'y':4})
d2 = ({'x':1, 'y':2}, {'x':5, 'y':6}, {'x':1, 'y':6, 'z':7})
I have two tuple d1
and d2
. I know tuples are immutable
. So I have to append another tuple using list. Is there any better solution.
Next question is How to uniqify a tuple on keys say 'x'. if 'x':1 in keys comes twice it is 开发者_如何学运维dulicate.
append_tuple = ({'x':1, 'y':2}, {'x':5, 'y':6}, {'x':1, 'y':6, 'z':7}, {'x':1, 'y':2}, {'x':3, 'y':4})
unique_tuple = ({'x':1, 'y':2}, {'x':3, 'y':4}, {'x':5, 'y':6})
Note: I want to remove the duplicate element from a tuple of dict if key values say 'x' has save value in two dict then those are duplicate element.
There is no better way to extend a tuple. I would say if you are constantly doing this, you need to migrate away from a tuple, or change your design.
Yet again it sounds like you are using the wrong type of collection. But you could remove the duplicated keys from the dictionary using the existing SO answer How to uniqufy the tuple element?
Tuples are generally for data where the number of items is fixed and each place has its own "meaning", so things like sorting, appending, and removing duplicates will never be very natural on tuples and weren't designed to be. If you're stuck with tuples, converting to a list, doing these operations, then converting back is perfectly reasonable.
For appending, you'd do:
d1 += (ITEM,)
and to extend, you'd just do:
d1 += d2
For uniquifying:
unique_list = []
for i1 in append_tuple:
if not any((k,v) in i2.items() for (k,v) in i1.items() for i2 in unique_list):
unique_list.append(i1)
unique_tuple = tuple(unique_list)
It might seem like there's a more concise/elegant solution, but what you are trying to do is fairly specific, and for stuff like this it's better to be explicit and build up the list in a for loop than to try to force it into a comprehension or similar.
精彩评论