1

So I have a list that looks like this:

users = [{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id':33, 'name': 'Third'}] 

What I want to do is to update a users name by passing id, creating new user, and replacing old one with new user. I want to get list of updated users, like this:

updated_users = list(map(update, users))

If I could send id to update func as argument, what I want to do, would look something like this:

def update(id):
    if user['id'] == id:
        new_user = some_fun()
        user = new_user
        return user

How should my update function look like?

3
  • How would you know the 'updated' ones ? Commented Dec 25, 2019 at 18:42
  • Yes, I know that map sends a user by argument to update(), but how do I chose wich user I want to edit? Commented Dec 25, 2019 at 18:52
  • 1
    why use map? why cant the update function just take an ID and a list of users and enumerate over the user list and update the matching user Commented Dec 25, 2019 at 18:59

1 Answer 1

1

I don't know why you want to use map and I think it's a wrong approach because map isn't for this kind of things (you could make it work for sure but it wouldn't be the way to go)

You can do something like that:

users = [{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id':33, 'name': 'Third'}]

def update(id, new_name):
    for user in users:
        if user["id"] == id:
            user["name"] = new_name
            return
    users.append({'id':id,'name':new_name}) # if not exist add user

print(users)
update(11,"Last")
update(1, "New_First")
print(users)

Output:

[{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id': 33, 'name': 'Third'}]
[{'id': 11, 'name': 'Last'}, {'id': 22, 'name': 'Second'}, {'id': 33, 'name': 'Third'}, {'id': 1, 'name': 'New_First'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.