E
E
estry2021-10-07 14:55:38
Python
estry, 2021-10-07 14:55:38

How to make a list from a value in a python dictionary?

Hello. There is a dictionary:
{0: "Hi", 1: "Monty", 2: "Python", 3: "snake", 4: "Anaconda"}
How can I add a name to a 0 key by converting it to a list?
For example, I need to get this from the dictionary above:
{0: ["Hi", "Hello"], 1: "Monty", 2: "Python", 3: "snake", 4: "Anaconda"}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Kuts, 2021-10-07
@estry

a = {0: "Hi", 1: "Monty", 2: "Python", 3: "snake", 4: "Anaconda"}
a[0] = [a[0], 'Hello']
print(a)
# {0: ['Hi', 'Hello'], 1: 'Monty', 2: 'Python', 3: 'snake', 4: 'Anaconda'}

0
0xD34F, 2021-10-07
@0xD34F

def append(data, key, val):
  if key not in data:
    data[key] = []
  elif type(data[key]) != list:
    data[key] = [ data[key] ]

  data[key].append(val)

A
alexbprofit, 2021-10-07
@alexbprofit

a = {0: "Hi", 1: "Monty", 2: "Python", 3: "snake", 4: "Anaconda"}
x = [a[0]]
x.append("Hello")
a[0] = x

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question