I want to unique duplicate values in a dict. It looks like this:
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
Here is what I did:
# sort and unique the dict values
obj = d.values()
K = []
K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0]
V=[]
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
d_out = dict(zip(K, V))
1. So, will the K,V be in a right order? Also, it may a bit complex, can anyone give a simple solution to unique a dict by it's values?
2. Can the following be more simple?
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
This is not working on my testing:
[V.append([k for k, v in obj.iteritems() if v == v1][0]) for v1 in L]
3. I realized I may use the swap key value to achieve that (unique a dict by its value), but I have no idea how to select the key when swap caused a key conflict with this:
dict((value, key) for key, value in my_dict.iteritems())
I know if swap it again the value will be unique, however, this just overwrites the key when a key conflict happens, giving no chance to make a selection. I feel confused why this gives no key conflict error? And can I do something to select the key beside the ugly way overwrite the new dict's key later?
4. I searched and find some "None" values for python dict are well discussed, anyone can give me a sample what it is used for and what it will impacted in using python dict?