So, I have a for loop that creates some dictionaries. On top of that, I want to add these dictionaries in a list. The for-loop works fine, and I am able to print the dictionaries separately, but when I try to append them to the list, I don't get the desired result. I just cant figure out what I'm doing wrong. Any help will be appreciated!

# This is the dictionary I'll be altering:
user = {'user': 'nikos', 'areas': [{'Africa': ['Kenya', 'Egypt']}, {'Europe': ['Brexit']}]}   
# these are some needed variables
user_new = [] # where the dictionaries will be added
sample_user = {} 

Here is my code:

for i in user['areas']: 
    sample_user['user'] = user['user'] 
    for key in i:
        sample_user['area'] = key #ok
        kword = i.get(key) 
        kword = '$'.join(kword) 
        sample_user['keywords'] = kword 
        user_new.append(sample_user)
        print(user_new)

The desired result for the print() is:

[{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'},
{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}]

but I get these two lists:

[{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'}]
[{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}, {'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}]

2 Answers

0
Blaydice On Best Solutions

If you want to stick to the code you have, you just need to move sample_user = {} inside your loop (and the print() outside). So the code would be:

for i in user['areas']:
    sample_user = {}
    sample_user['user'] = user['user']
    for key in i:
        sample_user['area'] = key #ok
        kword = i.get(key)
        kword = '$'.join(kword)
        sample_user['keywords'] = kword
        user_new.append(sample_user)
print(user_new)

Cause right now you're just overwriting the same dictionary.

0
Rakesh On

Using a simple iteration

Ex:

user = {'user': 'nikos', 'areas': [{'Africa': ['Kenya', 'Egypt']}, {'Europe': ['Brexit']}]}   
result = []

for i in user["areas"]:
    val = list(i.items())
    result.append({"user": user["user"], 'area': val[0][0], 'keywords': "$".join(val[0][1])})
print(result)

Output:

[{'area': 'Africa', 'keywords': 'Kenya$Egypt', 'user': 'nikos'},
 {'area': 'Europe', 'keywords': 'Brexit', 'user': 'nikos'}]