Home > Software engineering >  Assign dictionary value for every item in list of dictionaries
Assign dictionary value for every item in list of dictionaries

Time:04-30

Making some experiment with Python (3.8) and now I'm stuck with a probably silly problem.

I have a list of objects (actually, dictionaries) and I need to set a value for every entry in the list.

Say my object/dictionary is something like this:

{
    "name": "Joe",
    "surname": "Black" 
}

for every item in the list, I'd like to assign a new value: full_name: name " " surname.

At the moment I'm trying something like this (where records is my list of dictionaries):

records = map(lambda item: item["full_name"] = item["name"]   " "   item["surname"]; return item, records)

but probably this is not even valid Python syntax.

Can you suggest me the correct way to achieve this? Is there a way to implement it using for loop?

CodePudding user response:

Nothing wrong with a simple for-loop:

people = [{
    "name": "Joe",
    "surname": "Black" 
}]

for i in people:
    i["fullname"] =  i["name"]   " "   i["surname"]

CodePudding user response:

The above solution will work, but actual creates a copy of the list records with modification in the variable result; if you want to simply add the attribute to the existing items in the existing list you can do the following:

for record in records:
    record["fullname"] = f"{record['name']} {record['surname']}"

CodePudding user response:

Here is one way to solve this, Please note that this create entirely new list with dictionary objects.

>>> records = [{"name": "Joe1", "surname": "Black"}, {"name": "Joe2", "surname": "Black"}]
>>>
>>> result = [
...     {**record, "fullname": record["name"]   " "   record["surname"]}
...     for record in records
... ]
>>> print(result)
[{'name': 'Joe1', 'surname': 'Black', 'fullname': 'Joe1 Black'}, {'name': 'Joe2', 'surname': 'Black', 'fullname': 'Joe2 Black'}]
  • Related