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/02/26 03:18] – [tasks] rajupython_dictionaries [2023/08/02 19:41] (current) – [find key corresponding to a value] raju
Line 6: Line 6:
   * [[Convert a string to a dictionary]]   * [[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 119: Line 142:
  
 Ref:- http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression 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>
  
python_dictionaries.1677381531.txt.gz · Last modified: 2023/02/26 03:18 by raju