如果密钥已经在字典中,则增加密钥

问题描述 投票:0回答:2

如果键已经存在,我将尝试自动增加字典键

我已经使用while循环实现了,但是我想知道是否会有更干净/更快的方法来做到这一点

foo = {}
foo["a"] = "bar"
foo["a (1)"] = "baz"
key = "a"
count = 0
key_check = key
while key_check in foo:
    count += 1
    key_check = key + " ({})".format(count)

foo[key_check] = "bazzz"
print foo
>>>{'a': 'bar', 'a (1)': 'baz', 'a (2)': 'bazzz'}
python
2个回答
0
投票

我认为评论者试图解释的是,当您尝试执行此类操作时,您无需更改密钥的名称。相反,您可以构建逻辑,以便更新每个键/值对中的值。例如,在此代码段中,我有一个单词列表,我想知道每个单词有多少个。 “ except”之后的代码部分是在找不到密钥时触发的部分。这个示例与您的用例不完全匹配,但是我认为/希望它可以有效地说明整体观点。

tokens = ['now', 'when', 'i', 'say', 'that', 'i', 'am', 'in', 'the', 'habit', 'of', 'going', 'to', 'sea', 'whenever', 'i', 'begin', 'to', 'grow', 'hazy', 'about', 'the', 'eyes', 'and', 'begin', 'to', 'be', 'over', 'conscious', 'of', 'my', 'lungs', 'i', 'do', 'not', 'mean', 'to', 'have', 'it', 'inferred', 'that', 'i', 'ever', 'go', 'to', 'sea', 'as', 'a', 'passenger', 'for', 'to', 'go', 'as', 'a', 'passenger', 'you', 'must', 'needs', 'have', 'a', 'purse', 'and', 'a', 'purse', 'is', 'but', 'a', 'rag', 'unless', 'you', 'have', 'something', 'in', 'it', 'besides', 'passengers', 'get', 'sea', 'sick', 'grow', 'quarrelsome', 'dont', 'sleep', 'of', 'nights', 'do', 'not', 'enjoy', 'themselves', 'much', 'as', 'a', 'general', 'thing;', 'no', 'i', 'never', 'go', 'as', 'a', 'passenger;', 'nor', 'though', 'i', 'am', 'something', 'of', 'a', 'salt', 'do', 'i', 'ever', 'go', 'to', 'sea', 'as', 'a', 'commodore', 'or', 'a', 'captain', 'or', 'a', 'cook', 'i', 'abandon', 'the', 'glory', 'and', 'distinction', 'of', 'such', 'offices', 'to', 'those', 'who', 'like', 'them', 'for', 'my', 'part', 'i', 'abominate', 'all', 'honorable', 'respectable', 'toils', 'trials', 'and', 'tribulations', 'of', 'every', 'kind', 'whatsoever', 'it', 'is', 'quite', 'as', 'much', 'as', 'i', 'can', 'do', 'to', 'take', 'care', 'of', 'myself', 'without', 'taking', 'care', 'of', 'ships', 'barques', 'brigs', 'schooners', 'and', 'what', 'not', 'and', 'as', 'for', 'going', 'as', 'cook', 'though', 'i', 'confess', 'there', 'is', 'considerable', 'glory', 'in', 'that', 'a', 'cook', 'being', 'a', 'sort', 'of', 'officer', 'on', 'ship', 'board', 'yet', 'somehow', 'i', 'never', 'fancied', 'broiling', 'fowls;', 'though', 'once', 'broiled', 'judiciously', 'buttered', 'and', 'judgmatically', 'salted', 'and', 'peppered', 'there', 'is', 'no', 'one', 'who', 'will', 'speak', 'more', 'respectfully', 'not', 'to', 'say', 'reverentially', 'of', 'a', 'broiled', 'fowl', 'than', 'i', 'will', 'it', 'is', 'out', 'of', 'the', 'idolatrous', 'dotings', 'of', 'the', 'old', 'egyptians', 'upon', 'broiled', 'ibis', 'and', 'roasted', 'river', 'horse', 'that', 'you', 'see', 'the', 'mummies', 'of', 'those', 'creatures', 'in', 'their', 'huge', 'bake', 'houses', 'the', 'pyramids', 'no', 'when', 'i', 'go', 'to', 'sea', 'i', 'go', 'as', 'a', 'simple', 'sailor', 'right', 'before', 'the', 'mast', 'plumb', 'down', 'into', 'the', 'forecastle', 'aloft', 'there', 'to', 'the', 'royal', 'mast', 'head', 'true', 'they', 'rather', 'order', 'me', 'about', 'some', 'and', 'make', 'me', 'jump', 'from', 'spar', 'to', 'spar', 'like', 'a', 'grasshopper', 'in', 'a', 'may', 'meadow', 'and', 'at', 'first', 'this', 'sort', 'of', 'thing', 'is', 'unpleasant', 'enough', 'it', 'touches', 'ones', 'sense', 'of', 'honor', 'particularly', 'if', 'you', 'come', 'of', 'an', 'old', 'established', 'family', 'in', 'the', 'land', 'the', 'van', 'rensselaers', 'or', 'randolphs', 'or', 'hardicanutes', 'and', 'more', 'than', 'all', 'if', 'just', 'previous', 'to', 'putting', 'your', 'hand', 'into', 'the', 'tar', 'pot', 'you', 'have', 'been', 'lording', 'it', 'as', 'a', 'country', 'schoolmaster', 'making', 'the', 'tallest', 'boys', 'stand', 'in', 'awe', 'of', 'you', 'the', 'transition', 'is', 'a', 'keen', 'one', 'i', 'assure', 'you', 'from', 'a', 'schoolmaster', 'to', 'a', 'sailor', 'and', 'requires', 'a', 'strong', 'decoction', 'of', 'seneca', 'and', 'the', 'stoics', 'to', 'enable', 'you', 'to', 'grin', 'and', 'bear', 'it', 'but', 'even', 'this', 'wears', 'off', 'in', 'time']

result ={}
for i in tokens:
    try:
        result[i] +=1
    except:
        result[i] = 1

# result is {'now': 1,
# 'when': 2,
# 'i': 17,
# 'say': 2,
# 'that': 4,
# 'am': 2,
# 'in': 8,
# 'the': 16, ... }

0
投票

一种更简洁的方法是在键和它的值列表之间使用映射。为此使用defaultdict。如果不存在键,它将调用defaultfactory函数*并返回它。*这里的默认工厂功能是list函数,它返回一个空列表

from collections import defaultdict

# foo=[("a", "bar"), ("a", "bazz")] # some random input that maps keys to values, and keys repeat
foobarbaz = defaultdict(list) # return empty list if key doesn't exist
for k, val in foo:
    foobarbaz[k].append(val)
# If you don't want a simple dict instead of defaultdict
foobarbaz = dict(foobarbaz)
print(foobarbaz)
>>>{'a': ['bar', 'bazzz']}
© www.soinside.com 2019 - 2024. All rights reserved.