【问题标题】:How can I check that a value exists in a dictionary or not in python如何检查字典中是否存在值在python中
【发布时间】:2021-11-30 13:13:21
【问题描述】:
mydict = {}

while True:
    num = int(input())
    if num == 0 :
        break
    while num > 0:
        inp = input().split(" ")
        mylist = list(inp)

        for i in range(0,len(mylist)):

            if mylist[i] in mydict.values():
                print(f"Yes, Value: '{mylist[i]}' exists in dictionary")
            else:
                print(f"No, Value: '{mylist[i]}' does not exists in dictionary")
                mydict[mylist[i]] = 0

        print(mydict)

    
        for i in range(0,len(mylist)):
            if i == 0 :
                mydict[mylist[i]] += 3
            if i == 1 :
                mydict[mylist[i]] += 2
            if i == 2 :
                mydict[mylist[i]] += 1

        print(mydict)
        num-=1

这是我的代码,我不知道为什么它不明白字典中的某些值在添加后已经存在,我不希望他们将其更改为零

2
3 3 2 1
No, Value: '3' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 5, '2': 1, '1': 0}
3 2 3 1
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 4, '2': 2, '1': 0}
0

但我想要:

2            
3 3 2 1
No, Value: '3' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 5, '2': 2, '1': 0}
3 2 3 1
Yes, Value: '3' exists in dictionary
Yes, Value: '2' exists in dictionary
Yes, Value: '3' exists in dictionary
Yes, Value: '1' exists in dictionary
{'3': 5, '2': 2, '1': 0}
{'3': 9, '2': 4, '1': 0}
0

【问题讨论】:

  • 不要使用for i in range(len(some_list)):通过索引访问列表的值,使用for value in some_list:
  • @Barmar 但随后代码进入设置mydict[mylist[i]] = 0。我认为原始海报的 dict 键和值都混在一起了。
  • inp 已经是列表,不需要list(inp)
  • 你能用预定义的输入创建一个更简单的例子吗?键和值之间有更清晰的区别,而不是它们都是小整数?这对我来说太混乱了。
  • 为什么要在第二行写3 does not exist in dictionary?上一行将其添加到字典中。

标签: python python-3.x dictionary key-value


【解决方案1】:

您的要求还不清楚,但似乎这是您想要的(代码 cmets 中的解释):

# import zip_longest because it allows to zip shorter
# and longer iterators and replace the corresponding
# shorter iterator's values with None by default
from itertools import zip_longest

# define the main dictionary
dct = dict()
# this is the placement so that first
# gets added a value of 3 and so on
# this is why zip longest is needed
placement = [3, 2, 1]

# main loop
while True:
    # get input and .split it
    inp = input().split()
    # if no input was provided
    # stop the program
    if not len(inp):
        break
    
    # and now for the input and the placement, zip longest them
    for key, added_value in zip_longest(inp, placement):
        # first check if the key is in the dictionary
        if key in dct.keys():
            # if the key is in dictionary print this and already add the
            # corresponding value depending in which place
            # the key was located in input
            print(f'Key {repr(key)} is in the dictionary')
            if added_value is not None:
                dct[key] += added_value
        # in case user input is shorter just break this, so that
        # dictionary doesn't have None keys
        elif key is None:
            break
        else:
            # if the key wasn't in the dictionary set it to the 
            # value corresponding to placement
            print(f'Key {repr(key)} is not in the dictionary')
            dct[key] = added_value if added_value is not None else 0
    
    # print the current dictionary
    print(dct)

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多