Home > Software engineering >  Adding a list of strings to an existing key in a dict
Adding a list of strings to an existing key in a dict

Time:12-20

I am trying to add strings to a list(adding new strings in each loop with .append()), after that adding the list to an existing key. The problem is after adding the new string to the list and than to a key in console get printed [...](how to get rid of this [...]) example:

x = {}
y = ["going home"]
x["key"].append(y)
y.append("after lunch")
x["key"].append(y)
print(x)
{'key' : ['going home', 'after lunch', [...]]}

Thank you for your time

CodePudding user response:

Maybe the correct behavior is:

x = {}
y = ["going home"]
x["key"] = y
y.append("after lunch")
print(x)
{'key': ['going home', 'after lunch']}

CodePudding user response:

Another option is to use list.extend:

x = {}
x['key'] = []
y = ["going home"]
x["key"].extend(y)
y = ["after lunch"]
x["key"].extend(y)
print(x)

Output:

{'key': ['going home', 'after lunch']}
  • Related