Python access value for a single key in a multi key dictionary

60 views Asked by At

I have a DataFrame and tried to change the dtype. I can do it like this:

#Example
ds = ds.astype({'Breite':float,'Hoehe':float,'Tiefe':float,'vol':float,'Anzahl':np.int64},axis = 1)

I was wondering if I can shorten the dict a bit to have it more readable, like this:

shorter_dict = {('Breite','Hoehe','Tiefe','vol'):float,'Anzahl':np.int64}

ds = ds.astype(shorter_dict,axis=1)

But it want take value to each element from the tuple. With my search I found a module that does it:

from multi_key_dict import multi_key_dict

k[1000, 'kilo', 'k'] = 'kilo (x1000)'

print k[1000] # will print 'kilo (x1000)' print k['k'] # will also print 'kilo (x1000)'

the same way objects can be updated, deleted: and if an object is updated using one key, the new value will be accessible using any other key, e.g. for example above: k['kilo'] = 'kilo' print k[1000] # will now print 'kilo' as value was updated

My Question now is: Is there anything directly in python that does the same?


Edit: with some help from here stackoverflow.com/a/41075523/14065969 and here https://stackoverflow.com/a/41075515/14065969

I did this and it worked:

#Example
import pandas as pd
import numpy as np

shortdict = {('Breite','Hoehe','Tiefe','vol'):float,('Anzahl',):np.int64}

df = pd.DataFrame({'Breite':10,'Hoehe':20,'Tiefe':30,'vol':100,'Anzahl':400},index = [0])

print (df)
print(df.info(),'\n'*2)

for key,value in shortdict.items():
    for inner_key in key:
        df = df.astype({inner_key : value})

print (df)
print(df.info())

OUTPUT:

   Breite  Hoehe  Tiefe  vol  Anzahl
0      10     20     30  100     400
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Breite  1 non-null      int64
 1   Hoehe   1 non-null      int64
 2   Tiefe   1 non-null      int64
 3   vol     1 non-null      int64
 4   Anzahl  1 non-null      int64
dtypes: int64(5)
memory usage: 48.0 bytes
None 


   Breite  Hoehe  Tiefe    vol  Anzahl
0    10.0   20.0   30.0  100.0     400
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Breite  1 non-null      float64
 1   Hoehe   1 non-null      float64
 2   Tiefe   1 non-null      float64
 3   vol     1 non-null      float64
 4   Anzahl  1 non-null      int64  
dtypes: float64(4), int64(1)
memory usage: 48.0 bytes
None
[Finished in 0.7s]```
0

There are 0 answers