Home > Mobile >  How to access a value inside a value in a python dictionary
How to access a value inside a value in a python dictionary

Time:11-22


Im having a small concern if we can access a value inside a value.

Eg:
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}

As in the example above..
How can I print/access the value 4 in myDict?? Is it possible with indexing??
Eg: 4 # Printing 4 from myDict

Thanks.

CodePudding user response:

For this you need to convert string into array by dividing it by comma ",".

  1. Access 2nd element: result = myDict[1]
  2. Divide it by comma: result = result.split(",")
  3. Access element: ans = result[4]
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}
result = myDict[1].split(",")
ans = result[4]
print(ans)

CodePudding user response:

Or make a one line loop:

value = [i for i in myDict[2].split(',') if i == '4'][0]
  • Related