-1

I'm coding in Python and working with a JSON file that has 2 columns of data; a key, and the number of times that key was found in the data I'm working with. My goal is to remove all keys that are integers.

I've extracted the JSON as test_map, then used the keys() method which creates a dictionary(keys) of the keys. I'm attempting to loop through keys using isinstance to identify each integer key in keys. I have yet to get to the removal part, but I noticed that each key in keys are identified as strings, so isinstance isn't catching anything.

If anyone has any ideas as to how to code this to catch the int keys, then possibly to remove them, I would appreciate it. I believe the solution involves casting but I can't figure it out.

keys=test_map.keys()
for key in keys:
    if isinstance(key,int):
        print(f"key: {key}")

I've edited to include a sample of the JSON file below. I'm trying to remove the objects with integer keys.

    {
    "run": 121,
    "'988844333',": 4,    <remove
    "123": 27,            <remove
    "brown": 19,
    "face": 345,
    "21554,": 4,          <remove
    "gain": 4,
    }

2 Answers2

1

The .isdigit() method of string checks if the string is composed of just digits. Here's the doc

We can use that to filter keys that are ints.

Here's the code:

res = {k:v for k,v in test_map.items() if not k.isdigit()}
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
0

You can try casting like this. But you need to write a try except in case the key is not convertible to int.

keys = [key for key in test_map]
for key in keys:
    try:
        a = int(key)
        del test_map[key]
    except:
        pass
maede rayati
  • 756
  • 5
  • 10
  • thanks for the feedback. When I run this I get a runtime error: dictionary changed size during iteration. From what I've looked up, the issue is deleting from test_map while iterating. – Nick Picciano Jul 05 '20 at 16:41
  • Thanks for the comment, you are right, I have changed it to not refer to test_map keys but make copy of it. – maede rayati Jul 05 '20 at 22:19