Thursday, January 30, 2014

Python dictionaries

https://yuji.wordpress.com/2008/05/14/python-basics-of-python-dictionary-and-looping-through-them/



http://stackoverflow.com/questions/16772071/sort-dict-by-value-python

To get the values use
sorted(data.values())
To get the matching keys, use a key function
sorted(data, key=data.get)
To get a list of tuples ordered by value
sorted(data.items(), key=lambda x:x[1])
 
http://stackoverflow.com/questions/15785719/how-to-print-a-dictionary-line-by-line-in-python 
 
 
python-how-to-print-a-dictionarys-key 
 
for key, value in mydic.items() :
    print (key, value) 
 
watch-out-for-listdictkeys-in-python-3 
One of the reasons why someone might actually opt to perform a more expensive copying operation is because, with the pre-3.0 semantics, the keys() method is atomic,
 in the sense that the whole operation of converting all dictionary keys
 to a list is done while the global interpreter lock is held. Thus, it’s
 thread-safe to run dict.keys() with Python 2.X. 
 
iterating-over-dictionary-items-values-keys-in-python-3 
In Python 3, keys() returns a dict_keys object but if we use it in a for loop context for k in d.keys() then an iterator is implicitly created. So the difference between for k in d.keys() and for k in iter(d.keys()) is one of implicit vs. explicit creation of the iterator.
 
Revamping dict.keys(), .values() and .items()
 list(args.keys()) => []
 list(args.keys) => TypeError: 'builtin_function_or_method' object is not iterable 
args.keys is an iterator... 
 
Get the list "iterator"
>>> args.keys()
dict_keys(['WORKSPACE_REGRESSION_ROOT', '--runalltests', '--testsuite', 'TESTTYPE', 'TESTNAME', '--regression_workspace', '--testname', 'TESTSUITE', '--testtype']) 
 
Get the list  
>>> list(args.keys())
['WORKSPACE_REGRESSION_ROOT', '--runalltests', '--testsuite', 'TESTTYPE', 'TESTNAME', '--regression_workspace', '--testname', 'TESTSUITE', '--testtype'] 
 
Print the list
>>> '.'.join((args.keys()))
'WORKSPACE_REGRESSION_ROOT.--runalltests.--testsuite.TESTTYPE.TESTNAME.--regression_workspace.--testname.TESTSUITE.--testtype'
 
converting-python-dictionary-to-list 
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}

>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]

>> d.keys()
['a', 'b']

>> d.values()
['Arthur', 'Belling']