Create/Update dictionary form list


There is a straight forward way to update an existing or empty directory from given a list of keys. In the first example below, we update dict only with keys, which were not already present. Notice that the key ‘a’ did get change and ‘z’ did not get deleted – they were left alone. The second example, basically initializes an empty dict object. Whereas, the third example creates a new dict object which did not exist before.

Continue reading “Create/Update dictionary form list”

Python: Find closest from given dictionary values


Objective: I have a dictionary, and a float value. I would like to sort the dictionary in such a way that, first key-value pair’s value is nearest (min absolute difference) to a given float value, and last would be the farthest (max absolute difference)


>>> chooseFrom
{'1': 10.3438090737, '3': 7.73275047259, '2': 12.9046550095, '5': 10.3438090737, '4': 12.9046550095, '7': 7.88437303088, '6': 5.12169187146, '8': 0.0}
>>> gh
7.73275047259
# reference : http://stackoverflow.com/a/12141207/799593
>>> test = sorted(chooseFrom, key=lambda x:abs(chooseFrom[x]-gh))
>>> test
['3', '7', '1', '5', '6', '2', '4', '8']
>>> for x in test:
… print '{} : {} ==> {}'.format(x, chooseFrom[x], abs(gh-chooseFrom[x]))
3 : 7.73275047259 ==> 0.0
7 : 7.88437303088 ==> 0.15162255829
1 : 10.3438090737 ==> 2.61105860111
5 : 10.3438090737 ==> 2.61105860111
6 : 5.12169187146 ==> 2.61105860113
2 : 12.9046550095 ==> 5.17190453691
4 : 12.9046550095 ==> 5.17190453691
8 : 0.0 ==> 7.73275047259

Python: Compare Dictionaries



def compareDicts(d1, d2):
differences = []
# present in d1 but not in d2
for key, value in ({k: d1[k] for k in set(d1) – set(d2)}).iteritems():
temp = list[[key, value], None]
differences.append(temp)
# present in d2 but not in d1
diff2 = {k: d2[k] for k in set(d2) – set(d1)}
for key, value in (diff2).iteritems():
temp = [None, [key, value]]
differences.append(temp)
# updated from d1 to d2
updatedKeys = [item for item in list(set(d1.keys()) & set(d2.keys())) if d1.get(item) != d2.get(item)]
for key in updatedKeys:
temp = [[key, d1.get(key)],[key, d2.get(key)]]
differences.append(temp)
return differences
pass

view raw

compareDicts.py

hosted with ❤ by GitHub