I have a dictionary that looks like this:
dict = {id: ["gavin", "[email protected]", age, 55, [111, 222, 333]]}
There are more keys but that's not important. I want to be able to change the age value to be a number instead of age so the new dictionary would look like this
dict = {id: ["gavin", "[email protected]", 20, 55, [111, 222, 222]]}
It is the 3rd value of the "id" key.
I tried using the append() function but it just added a value at the end.
d["id"].append(20)
print(d)
The output just looks like this:
dict = {id: name, email, age, height, [value1, value2, value3], 20}
CodePudding user response:
In your particular case
dict[id][2] = 20
Change in yor dict key from id to "id"
dict["id"][2] = 20
Nothing wrong but: id is builtins def id(__obj: object) -> int Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)
CodePudding user response:
I'd say your question indicates two issues. The first is that your structure is a dictionary of lists and that you should therefore index into the list after indexing into the dictionary, and was answered effectively by @BrijeshVarsani.
However, your deeper issue is that you're attempting to encode data into a list when your data is not well-suited to that data type. The issue here is that each index associated with your list takes on an additional peace of information that the programmer has to understand explicitly. This results in an extremely fragile paradigm that will result in bugs in the future. Therefore, you should encode this information as a class:
class User:
def __init__(self, name, email, age, height, values):
self.name = name
self.email = email
self.age = age
self.height = height
self.values = values
dict = {id: User("gavin", "[email protected]", 20, 55, [111, 222, 222])}
dict["id"].age = 20
The advantage of this code is that it makes working with individual values much easier, which means you'll be able to understand your code implicitly which will result in much less time spent fixing bugs.