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:21] – [Convert a dictionary to a string] 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 154: Line 177:
 str str
 </code> </code>
 +
python_dictionaries.1677381673.txt.gz · Last modified: 2023/02/26 03:21 by raju