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"}
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"}
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']}
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]
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']}