-1

I am trying to get the first int value from all of the tuples in my dictionary keys. The problem is I keep getting the error: "ValueError: invalid literal for int() with base 10: 'Population'" The code I am using is

print([int(item[0]) for item in self.countryCat.values()])

Is there any way I can skip over the first value in my tuple which is "Population" so I will not get this error anymore? I have been stuck on this forever.

Thanks!

2 Answers2

0

You can make a generator that filters out the values that can't be cast to ints

def error_map(f, iterable):
    for item in iterable:
        try:
            yield f(item)
        except ValueError:
            continue

Then we can

print(list(error_map(lambda x: int(x[0]), self.countryCat.values())))
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

If you really want to use list comprehension, you need to make it a conditional list as described here and then for your condition, create a function that returns true/false if the string can be converted to a string as described here

def represent_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return 

print([int(item[0]) for item in self.countryCat.values() if represent_int(item[0])])
Zooby
  • 325
  • 1
  • 7