Python moving and deleting elements in a dictionary

Question:

I have dictionary like this:

{user1 : role1}, {user2 : role2}, {user1 : role2}

And I need to convert it to this:

{user1 : role1,role2}, {user2 : role2}

How can I do this?
I am listing users and their roles in GCP and trying to compose them to one csv file:

    for member in binding['members']:
    org_line={}
    org_line['ProjectID']=project
    org_line['IAM']=binding['members']
    org_line['Role']=binding['role']
    org_list.append(org_line)
Asked By: Boeefka

||

Answers:

You do not have a dictionary. Dictionaries cannot have duplicated keys. You can try this for yourself:

some_dict = {
    'user1':'x' ,
    'user1':'y' , 
    'user2': 'x'}

print(some_dict)

What happens in this case is that the key of user1 has its value of ‘x’ overwritten to a value of ‘y’.


What you actually have provided is a tuple of 3x separate dictionaries.

My solution isn’t elegant but it’s a starting point. There’s definitely other ways you could go about this.

x = {'user1' : 'role1'}, {'user2' : 'role2'}, {'user1': 'role2'}, {'user2': 'role44'}, {'user3': 'role1'}, {'user1': 'role69'}, {'user1': 'role69'}


# Creates a set of the unique users 
list_of_list_of_users = [list(individual_dict.keys()) for individual_dict in x]
list_of_users = [i[0] for i in list_of_list_of_users]
set_of_users = set(list_of_users)

# Creates an empty dictionary
user_role_dict = dict()

# Loads the dictionary with each user and sets their permissions to None
for user in set_of_users:
    user_role_dict[user] = None

# Iterate over each individual dictionary and builds out a list of their permissions
for individual_dict in x:
    for key, value in individual_dict.items():

        # If there isn't already a permission value for the user:
        if user_role_dict[key] == None:
            user_role_dict[key] = [value]

        # If there is already some permission value(s) for the user
        else:
            current_permissions = user_role_dict[key]
            current_permissions.append(value)
            # Set the value to be a list which is a set(unique) permissions:
            user_role_dict[key] = list(set(current_permissions))

If you print out the user_role_dict then this is the result:

{'user3': ['role1'],
 'user1': ['role1', 'role2', 'role69'],
 'user2': ['role2', 'role44']}
Answered By: lummers
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.