How to access a variable which has a colon in its name in Python?

Question:

I created this code below to extract each individual key as separate data frames. However, since the prim_keys contains colon in their name, e.g. '5091016:2', the resulting dataframes should be named something like data5091016:2. But, it is impossible to access these datafarmes just typing that. How can I access these dataframes?

primkeys = list(data.prim_key.unique())
grouped = data.groupby(['prim_key'])

for i in primkeys:
    globals()[f'data{i}'] = grouped.get_group(i)

Thanks already. Best.

Asked By: alperyildirim

||

Answers:

You can use a dict instead of create dynamically dataframes:

dfs = dict(list(df.groupby('prim_key')))

Now you can use dfs['5091016:2'].

Answered By: Corralien

You can set whatever key you want in globals(), but if it’s not an identifier (or isn’t even a string!) it isn’t a variable because the language can’t access it (short of manually constructing bytecode objects). If you want to change your keys to be identifiers (beyond prefixing with a letter, as you have already done), go for it.

Answered By: Davis Herring
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.