Home > OS >  Fetch value from dictionary
Fetch value from dictionary

Time:03-23

I have a dictionary like this and i want to get the values from it:

dict1 = {
"pet animal": ["dog","cat"]
}
x = dict1.values()
print(x)

This code gives an output like this:

dict_values([['dog', 'cat']])

but i want an output like this:

['dog', 'cat']

CodePudding user response:

Alright with the help of comments i can do it now. Ty.

dict1 = {
"pet animal": ["dog","cat"]
}
x = list(dict1.values())
for i in x:
    x = i
print(x)

CodePudding user response:

You can also use unpacking operator:

my_dict = {
"pet animal": ["dog","cat"]
}

print(*my_dict.values())   # ['dog', 'cat']

CodePudding user response:

One of the ways you can do this is that you can convert dict_values to the list so you can use this code:

Instead of this:

print(x)

Use This:

print(list(x)[0])

CodePudding user response:

You can use a for loop to get the desired result:

dict1 = {
"pet animal": ["dog","cat"]
}

for value in dict1.values():
    print(value)

Output: enter image description here

  • Related