[英]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.所以我对这个问题的目标是,给定 2 个字符串str1
和str2
,创建一个字典,使得str1
中的字符是键,而str2
中的相应字符是值。
ie. IE。 crackthecode('apple','byytr')
returns {'a':'b','p':'y','l':'t','e':'r'}
and if it is inconsistent, ie. crackthecode('apple','byytr')
返回{'a':'b','p':'y','l':'t','e':'r'}
如果不一致, IE。 crackthecode('apple','byptr')
then returns {}
, an empty dictionary. crackthecode('apple','byptr')
然后返回{}
,一个空字典。
This is my code, I'm just not sure how to do the inconsistent case.这是我的代码,我只是不确定如何处理不一致的情况。
PS. PS。 I cannot use zip
for this question.对于这个问题,我不能使用zip
。
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 .您可以使用使用EAFP 原理的此代码。
>>> 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)编辑:不使用enumerate
的相同代码(由 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.