Find all Key-Elements by the same Value in Dicts

前端 未结 4 513
谎友^
谎友^ 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:44

    Here's a naive implementation. Someone with better Python skills can probably make it more concise and awesome.

    dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
    
    new_dict = {}
    for pair in dict.items():
        if pair[1] not in new_dict.keys():
            new_dict[pair[1]] = []
    
        new_dict[pair[1]].append(pair[0])
    
    print new_dict
    

    This produces

    {'a': ['abc', 'gh'], 'b': ['cdf'], 'g': ['fh', 'hfz']}
    

提交回复
热议问题