Python : sort int list based on another


This post discusses how to custom sort one list in python based on the order of elements of another list.

Continue reading “Python : sort int list based on another”

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(ghchooseFrom[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

Getting Started: Python


I personally think that Visual Studio is the best IDE, and I spend most of my day in it. And I’d definitely by using Visual Studio as much as I can –  if you are on Windows, Visual Studio’s Python support is worth exploring.

I’d leave the choice up to you. Both IDE have free and paid options.

I think Visual Studio is an engineering marvel. If as much effort went into space travel as went into the design of this, we’d be on Mars by now.

That said if you  prefer to use PyCharm:

  • Please go to https://www.jetbrains.com/student/ and get your free full blown tools offered by Jet Brains, with all bells and whistles.
  • Here are two YouTube video series if you want:

Getting Started with PyCharm:

PyCharm Video Demos:

 

 

 

 

If you want to use Visual Studio: