如何在 Python 字典中忽略输入的未定义键时执行操作:

huangapple go评论115阅读模式
英文:

what to do to ignore the output when undefined keys are inputted in python dictionary

问题

# 目标是找到两个数组的共同元素
# 在输入具有不在列表A中的值的情况下,这里会出现错误。

import numpy as np

A = np.random.randint(1, 10, 15)
B = np.random.randint(1, 15, 15)

print(A)
print(B)

dic = {}

for x in A:
    dic[x] = 1

for y in B:
    if y in dic:
        print("共同元素是", y)

# 我知道有使用集合、for循环和if条件的方法可以完成这个任务。我只是好奇是否可以使上述代码工作。
# 在这里,我旨在找到两个列表中的共同元素。
# 第一个列表的值用于设置字典的键。
# 代码在此处崩溃 --- `if dic[y]!=None:`
# 有没有办法使这段代码工作?
英文:

the objective is to find the common element of the two array

here error comes when dictionary is inputted with values not present in the list A.

import numpy as np

A=np.random.randint(1,10,15)

B=np.random.randint(1,15,15)

print(A)

print(B)

dic={}

for x in A:
    dic[x]=1

for y in B:
      if dic[y]!=None:
         print("the common element is  ", y)

I know there are ways like set, for and if, methods to do this. I am just curious whether the above code can be made to work.

Here i am aiming for finding the common elements in two lists.
the values of the first list is used to set keys of the dictionary.
the code crashes at this point --- if dic[y]!=None:

is there any way by which we can make this code work?

答案1

得分: 0

当调用dictionary[key]但键不存在时,它会引发KeyError,除非你使用try和except捕获它,否则会终止你的程序。另一种方法是使用dictionary.get(key),在缺少键的情况下返回None。

英文:

When dictionary[key] is called but the key doesn’t exist, it raises a KeyError, which terminates your program unless you catch it with try and except. An alternative is using dictionary.get(key), which returns None in the case of a missing key.

答案2

得分: 0

由于字典是由伪随机键构建的,其关联值为1,因此在这种情况下使用dict.get()是合理的。这是因为如果dict.get()返回None,那么您可以断定该键不存在。

但是,这并不是一个通用的解决方案。不要忘记None是一个有效的值。因此,使用dict.get()并不一定会告诉您键的存在与否。

以下是一个更健壮的方法:

import numpy as np

A = np.random.randint(1, 10, 15)
B = np.random.randint(1, 15, 15)

d = {n: 1 for n in A}

for y in B:
    if y in d:
        print(f'Common element {y}')

输出(示例):

Common element 5
Common element 3
Common element 2
Common element 1
Common element 3
Common element 5

请注意,在这种情况下,值5和3在输出中重复出现。虽然它们在两个列表(实际上是numpy.ndarray)中都是常见的,但重复它们并不是真正有意义的。

一个改进的方法是查看两个集合的交集,如下所示:

print(set(A) & set(B))

...在这种情况下,输出如下:

{1, 2, 3, 5}
英文:

As the dictionary is constructed with pseudo-random keys with 1 as their associated value, it is reasonable to use dict.get() in this case. That's because if dict.get() returns None then you can assert that the key is absent.

However, that is not a general solution. Don't forget that None is a valid value. Therefore, using dict.get() doesn't necessarily inform you of the existence (or otherwise) of a key.

Here's a more robust approach:

import numpy as np

A = np.random.randint(1,10,15)
B = np.random.randint(1,15,15)

d = {n: 1 for n in A}

for y in B:
    if y in d:
        print(f'Common element {y}')

Output (sample):

Common element 5
Common element 3
Common element 2
Common element 1
Common element 3
Common element 5

Notice how in this case the values 5 and 3 are repeated in the output. Whilst it is true that they are common in both lists (actually numpy.ndarray) it doesn't really make sense to repeat them.

An improved approach would be to look at the intersection of two sets as follows:

print(set(A) & set(B))

... which, in this case gives:

{1, 2, 3, 5}

huangapple
  • 本文由 发表于 2023年7月14日 00:15:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定