Find all Key-Elements by the same Value in Dicts

前端 未结 4 507
谎友^
谎友^ 2020-12-06 06:02

I have question about Dictionaries in Python.

here it is:

I have a dict like dict = { \'abc\':\'a\', \'cdf\':\'b\', \'gh\':\'a\', \'fh\':\'g\', \'hfz\'

4条回答
  •  执念已碎
    2020-12-06 06:34

    If you do specifically want tuples as the values in your new dictionary, you can still use defaultdict, and use tuple concatenation. This solution works in Python 3.4+:

    from collections import defaultdict
    
    source = {'abc': 'a', 'cdf': 'b', 'gh': 'a', 'fh': 'g', 'hfz': 'g'}
    target = defaultdict(tuple)
    
    for key in source:
        target[source[key]] += (key, )
    
    print(target)
    

    Which will produce

    defaultdict(, {'a': ('abc', 'gh'), 'g': ('fh', 'hfz'), 'b': ('cdf',)})
    

    This will probably be slower than generating a dictionary by list insertion, and will create more objects to be collected. So, you can build your dictionary out of lists, and then map it into tuples:

    target2 = defaultdict(list)
    
    for key in source:
        target2[source[key]].append(key)
    
    for key in target2:
        target2[key] = tuple(target2[key])
    
    print(target2)
    

    Which will give the same result as above.

提交回复
热议问题