简体   繁体   English

如何检测将具有不同值的相同键插入到字典中?

[英]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 个字符串str1str2 ,创建一个字典,使得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.

相关问题 dict理解我如何得到一个键的值除以同一个键但在不同的dict中的值 - dict comprehension how do i get the value of a key divided by a value of the same key but in a different dict 如何将dict {key:value}放入字典中的指定键中,以便在对value进行计数后成为{key:{key:value}} - How would I put a dict {key: value} in it's designated key in a dictionary so that it is {key: {key: value}} after counting value 如果按字典值对字典进行排序,我该如何按值对字典进行排序? - How would I sort this Dictionary by value then if the same sort it by key value? 如何通过相同的键值对dict元素求和 - How sum dict element by same key value 如果存在,如何比较Dict 1中键的值是“ ==”或Dict2中相同键的“!=”值 - How to compare the value of the key in Dict 1 is “==” or“!=” value of the same key in Dict2,if exists 如何遍历数据框并创建一个将列名存储为键并将相应行索引存储为值的字典? - How would I loop over a data frame and create a dict that stores the column name as a key and the corresponding row index as a value? 我将如何切片字典中的键值 - How would I slice a value of a key in a dictionary 如果键已包含在字典中,如何以智能方式将新的键值对添加到字典中? - How do I add a new key-value pair in a smart way to a dict if the key is already contained in the dict? python json dict iterate {key:value}是一样的 - python json dict iterate {key: value} are the same 检查 python 的字典中的键值是否相同 - Check if key value is the same in a dict in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM