简体   繁体   中英

How would I detect insertion of the same key with a different value into a dict?

So my goal for this problem is to, given 2 strings, str1 and str2 , create a dictionary such that the characters in str1 are the keys and the corresponding characters in str2 are the values.

ie. crackthecode('apple','byytr') returns {'a':'b','p':'y','l':'t','e':'r'} and if it is inconsistent, ie. crackthecode('apple','byptr') then returns {} , an empty dictionary.

This is my code, I'm just not sure how to do the inconsistent case.

PS. I cannot use zip for this question.

Below is my code.

def crackthecode(str1, str2):
  final = {}
  x = 0
  for i in list(str1):
    final[i]=str2[x]
    x = x + 1
  return final

All help is appreciated, thanks!

You can check if the key is already present in the dictionary, and compare the value with the new character. If they are not equal, return an empty dictionary. Otherwise, add the key-value pair to the dictionary.

You can use this code which uses the EAFP principle .

>>> def crackthecode(str1, str2):
    final = {}
    for i, key in enumerate(str1):
        try:
            if final[key] != str2[i]:
                return {}
        except KeyError:
            final[key] = str2[i]
    return final

>>> crackthecode('apple','byytr')
{'a': 'b', 'p': 'y', 'l': 't', 'e': 'r'}
>>> crackthecode('apple','byptr')
{}

Edit: Same code without using enumerate (requested by OP)

def crackthecode(str1, str2):
    final = {}
    for i in range(len(str1)):
        try:
            if final[str1[i]] != str2[i]:
                return {}
        except KeyError:
            final[str1[i]] = str2[i]
    return final 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM