4

First of all I know that out there are many similar posts which I have listed below, however, none to my knowledge answer the problem I'm facing this is because all that I have found are asking how to search for a string in 'dict.values()' and not to search every single character in the string and check whether it is in the 'dict.values()' and if it has found any characters in the string that appear in the characters of 'dict.values()' it will return which and how many.

Links to similar posts which don't answer the question but could be useful to some:

How to search if dictionary value contains certain string with Python

Find dictionary items whose key matches a substring

How can I check if the characters in a string are in a dictionary of values?

How to search if dictionary value contains certain string with Python

This is what I have so far but don't seem to work at all...

characters = {'small':'abcdefghijklmnopqrstuvwxyz',
              'big':'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
              'nums':'0123456789',
              'special':"!#$%&()*+,-./:;<=>?@[\]^_{|}~",}

password = 'aAb'

def count(pass_word,char_set):

    num_of_char = 0
    char_list = []

    for char in pass_word:
        if i in char_set.values():
            num_of_char +=1
            char_list += i

    return char_list, num_of_char


#Print result

print(count(password,characters))

The output should be something similar to:

'a','A','b'
3

Hopefully, you understand what I mean and if anything unclear please comment so that I can improve it.

Ivan
  • 117
  • 1
  • 1
  • 9

1 Answers1

1
def count(password, char_dict):
    sanitized_pass = [char for char in password if any(char in v for v in char_dict.values())]
    return sanitized_pass, len(sanitized_pass)

Here's one way. Another would be to build a set of all the acceptable c characters and pass that to the function with the password

from itertools import chain


char_set = set(chain.from_iterable(characters.values()))

def count(password, chars):
    sanitized_pass = [char for char in password if char in char_set]
    return sanitized_pass, len(sanitized_pass)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • Hey, im just wondering what would the code be to print out from which 'dict.key()' each character was found in? – Ivan Nov 18 '17 at 15:53
  • 1
    @Ivan I'm not sure I understand. Do you mean trying to identify which alphabet we use to replace a certain character? If there are duplicates, later entries will overwrite earlier ones, so whichever alphabet is closer to the end of the `alphabets` iterable will be used – Patrick Haugh Nov 18 '17 at 16:35