Home > Software design >  How to extract dict values and set as int variable?
How to extract dict values and set as int variable?

Time:05-22

What I want to do is to extract the value of a dictionary to do calculations with it. My dictionary only has one value. But I'm not able to do calculations ( -*/) with dictionary values and I don't find a way to assign the value to an int variable.

a = {'number': 5}
b = a.values()
c = b*3
print(c)

The code produces the error:

TypeError: unsupported operand type(s) for *: 'dict_values' and 'int'

CodePudding user response:

a.values() returns all the values of the dictionary as a dict_values.

Of course, in your case that's only one value, but it's still in that form.

One thing that would work in this case:

a = {'number': 5}
b = a.values()
c = list(b)[0]*3
print(c)

The dict_values itself is a so-called view of the values of the dictionary, for reasons that are a bit too complicated to go into here - but as a result they cannot be indexed directly, so c = b[0]*3 wouldn't work either.

Instead, the dict_values is cast into (forced into a certain type) a list, and the list can be indexed, so list(b)[0]*3 takes the list of values, select the first ([0]) element, and multiplies that by 3.

But what makes more sense:

a = {'number': 5}
b = a['number']
c = b*3

This just uses the dictionary as intended and selects the 'number' value by indexing the dictionary with the key a['number'].

Or:

a = {'number': 5}
b = list(a.values())
c = [x*3 for x in b]

Since the dictionary could have more than one value, you could also take the list of values and multiply each element by 3 individually. But the result would have to be another collection, like this list.

CodePudding user response:

Also, if you do not want to use list or list comprehension you can simply use:

a = {'number': 5}
for x in a.values():
   b=int(x)
c = b*3

Or as I commented:

a = {'number': 5}
b = a['number']
c = b*3
  • Related