Doug
Doug

Reputation: 597

getting keys in a dictionary that do not contain "x" variable Python

I have the following dictionary

dictionary = {'\x85': 1, '\x84': 1, 'C': 3828}

What I want is only the keys and corresponding values for keys that don't contain digits, this is what I wrote but it's not working. I'm getting a key error. I import re at the top by the way.

new_dictionary = {}   
for key in diciontary:  
      if r"\d" not in key:  
              new_dictionary[key] += dictionary[key]

this isn't working however, i'm getting a key error. Which I think means that key doesn't exist, but that's exactly what I want, everything but the keys with digits.

My expected output in this case is
dictionary = {'C': 3828}

Although I think I may be having troubles because the key is a string and even though there is a digit in it i think it's read a string, so the regex wouldn't work here?

This is actually a part of a huge dictionary, and this code I have pasted here worked for other instances in which there was a digit, however there were some that came through? Is that because the acutal characters were saved as different types? Either way, I'm not sure how to remove them.

Upvotes: 0

Views: 365

Answers (3)

wim
wim

Reputation: 363616

You seem to be confused about what those strings like '\x85' actually are. These are not necessarily strings with digits in them. They are escape sequences.

\xhh    Character with hex value hh

Nobody can tell you how to strip them out unless you more clearly identify what is the problem with them, and what characters you want remaining in the output.

For example, '\x43' is another way of representing the string 'C' in python, so the following two dicts are actually equal!

>>> dict1 = {'\x85': 1, '\x84': 1, 'C': 3828}
>>> dict2 = {'\x85': 1, '\x84': 1, '\x43': 3828}
>>> dict1 == dict2
True

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174874

You need to use regex pattern inside search or match function. So change the if condition to,

if not re.search(r"\d", key): 

OR

>>> dictionary = {'\x85': 1, '\x84': 1, 'C': 3828}
>>> {i:j for i,j in dictionary.items() if re.search(r'[A-Za-z]', i)}
{'C': 3828}

This would print the dictionary item if there is a single letter found on the key.

Upvotes: 3

Aziz Alfoudari
Aziz Alfoudari

Reputation: 5263

new_dictionary = {k:v for k,v in dictionary.iteritems() if k.isalpha()}

Upvotes: 3

Related Questions