[英]dict comprehension how do i get the value of a key divided by a value of the same key but in a different dict
[英]How would I detect insertion of the same key with a different value into a dict?
所以我對這個問題的目標是,給定 2 個字符串str1
和str2
,創建一個字典,使得str1
中的字符是鍵,而str2
中的相應字符是值。
IE。 crackthecode('apple','byytr')
返回{'a':'b','p':'y','l':'t','e':'r'}
如果不一致, IE。 crackthecode('apple','byptr')
然后返回{}
,一個空字典。
這是我的代碼,我只是不確定如何處理不一致的情況。
PS。 對於這個問題,我不能使用zip
。
下面是我的代碼。
def crackthecode(str1, str2):
final = {}
x = 0
for i in list(str1):
final[i]=str2[x]
x = x + 1
return final
感謝所有幫助,謝謝!
您可以檢查該鍵是否已存在於字典中,並將該值與新字符進行比較。 如果它們不相等,則返回一個空字典。 否則,將鍵值對添加到字典中。
您可以使用使用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')
{}
編輯:不使用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.