'Python dictionary, how can I create a key with a string and the actual key combined?

I hope this is a quite easy question, but for me without a lot of python background I can't find an answer.

df = pd.DataFrame(
    {'Messung': ['10bar','10bar','10bar','20bar','20bar'],  
     'Zahl': [1, 2, 3, 4, 5],  
     'Buchstabe': ['a','b','c','d','e']})  

There is a DataFrame (made a simplier Test DF for this post) where I loop through one column and compare the first 2 numbers of a string. The whole column has in the end like 20 Keys. Everytime the key is found, append the whole row to this key.

d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    if key not in d:
        d[key] = []
    d[key].append(df.iloc[row])

This code works, but my first attempt to this was different. I wanted to have dictionaries where I have keys named as 'RP_10', 'RP_20'.

d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    if key not in d:
        d['RP_'+key] = []
    d['RP_'+key].append(df.iloc[row])

Can someone explain to me, why this doesn't work and how could I write the code so that I get 'RP_10', 'RP_20' and so on?



Solution 1:[1]

Can you please try below code. You do small mistake in if condition.

d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    key = "RP_"+key
    if key not in d:
        d[key] = []
    d[key].append(df.iloc[row])

ALso you can use setdefault() of python.Then your code looks like as below:

d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    key = "RP_"+key
    d.setdefault(key, []).append(df.iloc[row])

Solution 2:[2]

While trying your solution I noticed, I can even delete the line with key=item[0:2] and directly build my key with 'RP_' and the item[0:2]

d={}
for row, item in enumerate(df['Messung']):
    key = "RP_"+item[0:2]
    d.setdefault(key, []).append(df.iloc[row])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kapil Rupavatiya
Solution 2 Rabinzel