0

Is there any way to extend a dictionary in python?
I would like to have more than one value in one key.

a = { "abc" : "cbd" , "asd" , "asd"}
mohammed wazeem
  • 1,310
  • 1
  • 10
  • 26

3 Answers3

1

I would like to have more then a one value in one key.

I think if you would like to have more than one value in one key it makes more sense having a list as value?

a = { "abc" :["cbd"] , "asd": ["asd"]}
print(a)
#adding new element
if a.get("abc",False): 
   a["abc"].append("new_item")
else:
   a["abc"] = ["new_item"]

print(a)

Would return something like

{'abc': ['cbd'], 'asd': ['asd']}
{'abc': ['cbd', 'new_item'], 'asd': ['asd']}
vestland
  • 55,229
  • 37
  • 187
  • 305
larek_aks
  • 29
  • 3
0

You can use this:

a = { "abc" : "cbd"}
a["abc"] = ["cbd", "asd", "fgh"]  # change the value of "abc" to be a list of your choice of values

In the list you put anything you want.

If you need the key's value for example "fgh" you can do this:

a["abc"][2]
Cappi
  • 21
  • 4
0

Create a list as the value of the dict and append:

a = { "abc" : ['1']
a["abc"].append('2')
print(a)  # {'abc': ['1', '2']}

EDIT:

You can have the duplicate values in the list as well:

a = { 'abc' : ['cbd']}

a['abc'].append('asd')
a['abc'].append('asd')

print(a)

OUTPUT:

{'abc': ['cbd', 'asd', 'asd']} 
DirtyBit
  • 16,613
  • 4
  • 34
  • 55