Add item to dictionary (array inside of a dictonary?)

Viewed 65
dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}

print(dic)
dic["t"] = dic["t"].append({"x": 3})
print(dic)

Actual result: {'t': None}

Wanted result: {'t': [{'x': 0}, {'x': 1}, {'x': 2}, {"x": 3}]}

Is probably simple I just do not really know what to search for.

3 Answers

The append method is in place, it does not output anything (well, it outputs None). When you run dic["t"] = dic["t"].append({"x": 3}), you replace the initial list with None.

You need to do:

dic["t"].append({"x": 3})

Full code:

dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}
print(dic)
dic["t"].append({"x": 3})
print(dic)

output:

{'t': [{'x': 0}, {'x': 1}, {'x': 2}]}
{'t': [{'x': 0}, {'x': 1}, {'x': 2}, {'x': 3}]}

append() returns None and not the list on which you apply the method as you expect. Change:

dic["t"] = dic["t"].append({"x": 3})

To:

dic["t"].append({"x": 3})

Another option is to do the following:

dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}

print(dic)
dic["t"] += [{"x": 3}]
print(dic)

Try doing only dic["t"].append({"x":3}) because append updates the list but returns None so your new value will be None. Instead, just update the value.

Related