0

Dfs is a dict with dataframes and the keys are named like this: 'datav1_135_gl_b17' We would like to calculate a matrix with constants. It should be possible to assign the values in the matrix according to the attributes from the df name. In this example '135' and 'b17'.

If you want code to create an example dfs, let me know, I've cut it out to more clearly state the problem.

We create a nested dict dynamically with the following function:

def ex_calc_time(dfs):
  formats = []
  grammaturs = []

  for i in dfs:
    # (...)

    # format
    split1 = i.split('_')
    format = split1[-1]
    format.replace(" ", "")
    formats.append(format)
    formats = list(set(formats))
    
    # grammatur
    # split1 = i.split('_')
    grammatur = split1[-3]
    grammatur.replace(" ", "")
    grammaturs.append(grammatur)
    grammaturs = list(set(grammaturs))
    # END FLOOP

  dict_mean_time = dict.fromkeys(formats, dict.fromkeys(grammaturs, ''))
  
  return dfs, dict_mean_time

Then we try to fill the nested dict and change the values like this (which should be working according to similiar nested dict questions, but it doesn't). 'Nope' is updated for both keys:

ex_dict_mean_time['b17']['170'] = 'nope'
ex_dict_mean_time

{'a18': {'135': '', '170': 'nope', '250': ''},
 'b17': {'135': '', '170': 'nope', '250': ''}}

I also tried creating a dataframe from ex_dict_mean_time and filling it with .loc, but that didn't work either (df remains empty). Moreover I tried this method, but I always end up with the same problem and the values are overwritten. I appreciate any help. If you have any improvements for my code please let me know, I welcome any opportunity to improve.

  • 1
    seems like the same reference is used for different values of the dictionary, which means updating one object shows changes on all instances the reference is used – Numan Ijaz Mar 22 '22 at 11:19
  • 1
    Question has too much code and is confusing the issue. Please trim your code to make it easier to find your problem. Follow these guidelines to create a minimal reproducible example. https://stackoverflow.com/help/minimal-reproducible-example – D.L Mar 22 '22 at 11:34
  • I trimmed the code and hope the problem is stated more clearly now. – Marvin Langer Mar 26 '22 at 10:30
  • `dict.fromkeys` does **not** clone the object for each key. It uses the same value for each key. Basically it is only suitable for immutable values or in cases where you do not modify the values. Replace it with `{f: dict.fromkeys(grammaturs, '') for f in formats}` and it should work – Bakuriu Mar 26 '22 at 10:35

0 Answers0