-1

How can I create a new dictionary from an existing dictionary to include only key and values where values are numeric?

Example dictionary:

simple_dict = {
  'a': 1, 
  'b': 2, 
  'c': 3, 
  'd': 'John',
  'e': 4,
  'f': 'Sandra'
}

What I have so far:

new_dict = {key: value for key, value in simple_dict.items() if }

I've tried using something like isdigit() or isnumeric() but keep receiving errors.

parrtakenn
  • 37
  • 4
  • 2
    Does this answer your question? [What is the most pythonic way to check if an object is a number?](https://stackoverflow.com/questions/3441358/what-is-the-most-pythonic-way-to-check-if-an-object-is-a-number) `isdigit` and `isnumeric` are _string_ methods – Pranav Hosangadi Nov 22 '22 at 23:05
  • Try this - ```new_dict = {key: value for key, value in simple_dict.items() if not isinstance(value, str) }``` – Daniel Hao Nov 22 '22 at 23:13

1 Answers1

1
import numbers
...
new_dict = {
    key:value for key, value in simple_dict.items()
    if isinstance(value, numbers.Number)
}
ekrall
  • 192
  • 8