User Tools

Site Tools


python_dictionaries

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python_dictionaries [2023/01/01 15:58] – [tasks] rajupython_dictionaries [2023/08/02 19:41] (current) – [find key corresponding to a value] raju
Line 1: Line 1:
 ==== tasks ==== ==== tasks ====
-group | related items, sort by | descending order of (nontriviality, interestingness, and usefulness)+Policy: group | related items, sort by | descending order of (nontriviality, interestingness, and usefulness etc.,)
  
   * [[convert dict of dicts to list of dicts]]   * [[convert dict of dicts to list of dicts]]
   * [[Convert a dictionary of dataframes to a big dataframe]]   * [[Convert a dictionary of dataframes to a big dataframe]]
 +  * [[Convert a string to a dictionary]]
 +
 +
 +==== find key corresponding to a value ====
 +The following will find the first key corresponding to a given value
 +<code>
 +>>> d ={1:'A', 2:'B', 3:'A', 4:'B'}
 +>>> key_list = list(d.keys())
 +>>> val_list = list(d.values())
 +>>> lookup_val = 'A'
 +>>> position = val_list.index(lookup_val)
 +>>> key_val = key_list[position]
 +>>> print(key_val)
 +1
 +</code>
 +<code>
 +>>> lookup_val = 'B'
 +>>> position = val_list.index(lookup_val)
 +>>> key_val = key_list[position]
 +>>> print(key_val)
 +2
 +</code>
 +
 +Sample use case:
 +  * In https://github.com/KamarajuKusumanchi/notebooks/blob/master/finvizfinance/target_price.ipynb , I used the above technique to find the index corresponding to 'Target Price'.
  
 ==== initialize a dictionary ==== ==== initialize a dictionary ====
Line 14: Line 39:
 Out[1]: Out[1]:
 {'sun': 1, 'mon': 2, 'tue': 3} {'sun': 1, 'mon': 2, 'tue': 3}
 +</code>
 +
 +==== dump dictionary to file ====
 +You can use pprint (stands for pretty print)
 +
 +<code>
 +$ ipython
 +Python 3.10.9 | packaged by conda-forge | (main, Jan 11 2023, 15:15:40) [MSC v.1916 64 bit (AMD64)]
 +IPython 8.8.0 -- An enhanced Interactive Python. Type '?' for help.
 +
 +In [1]:
 +import pprint
 +cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
 +pprint.pformat(cats)
 +Out[1]:
 +"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
 +
 +In [2]:
 +fileObj = open('myCats.py', 'w')
 +fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
 +fileObj.close()
 +
 +In [3]:
 +exit()
 +</code>
 +
 +<code>
 +$ cat myCats.py
 +cats = [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]
 +</code>
 +
 +<code>
 +$ ipython
 +Python 3.10.9 | packaged by conda-forge | (main, Jan 11 2023, 15:15:40) [MSC v.1916 64 bit (AMD64)]
 +IPython 8.8.0 -- An enhanced Interactive Python. Type '?' for help.
 +
 +In [1]:
 +import myCats
 +myCats.cats
 +Out[1]:
 +[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]
 +
 +In [2]:
 +myCats.cats[0]
 +Out[2]:
 +{'desc': 'chubby', 'name': 'Zophie'}
 +
 +In [3]:
 +myCats.cats[0]['name']
 +Out[3]:
 +'Zophie'
 +
 +In [4]:
 +exit()
 +</code>
 +
 +Ref:-
 +  * pprint is discussed in https://automatetheboringstuff.com/2e/chapter9/ -> Saving Variables with the pprint.pformat() Function
 +
 +==== merge python dictionaries ====
 +
 +To merge two python dictionaries
 +<code>
 +def merge_two_dicts(x, y):
 +    '''
 +    Given two dicts, merge them into a new dict as a shallow copy.
 +    For common keys, the values in y take precedence over values in x.
 +    '''
 +    z = x.copy()
 +    z.update(y)
 +    return z
 +</code>
 +
 +Sample usage:
 +<code>
 +>>> x = {'a': 1, 'b': 2}
 +>>> y = {'b': 3, 'c': 4}
 +>>> z = merge_two_dicts(x, y)
 +>>> z
 +{'a': 1, 'c': 4, 'b': 3}
 +</code>
 +
 +
 +To merge an undefined number of dicts
 +<code>
 +def merge_dicts(*dict_args):
 +    '''
 +    Given any number of dicts, shallow copy and merge into a new dict,
 +    precedence goes to key value pairs in latter dicts.
 +    '''
 +    result = {}
 +    for dictionary in dict_args:
 +        result.update(dictionary)
 +    return result
 +</code>
 +
 +Given dicts a to g
 +<code>
 +z = merge_dicts(a, b, c, d, e, f, g) 
 +</code>
 +will give a new dict z with all the key-value pairs. If same key exists in multiple dictionaries, the right most one will take precedence.
 +
 +Ref:- http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression
 +
 +==== Convert a dictionary to a string ====
 +<code>
 +$ ipython
 +Python 3.10.6 | packaged by conda-forge | (main, Oct 24 2022, 16:02:16) [MSC v.1916 64 bit (AMD64)]
 +Type 'copyright', 'credits' or 'license' for more information
 +IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
 +
 +In [1]:
 +d = {'a':1, 'b':2}
 +
 +In [2]:
 +import json
 +s = json.dumps(d)
 +
 +In [3]:
 +d
 +Out[3]:
 +{'a': 1, 'b': 2}
 +
 +In [4]:
 +s
 +Out[4]:
 +'{"a": 1, "b": 2}'
 +
 +In [5]:
 +type(d)
 +Out[5]:
 +dict
 +
 +In [6]:
 +type(s)
 +Out[6]:
 +str
 </code> </code>
  
python_dictionaries.1672588685.txt.gz · Last modified: 2023/01/01 15:58 by raju