Multiple keys per value

后端 未结 7 1403
抹茶落季
抹茶落季 2020-12-01 11:58

Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key:

dict = {\'k1\':\'v1\', \'k2\':         


        
7条回答
  •  生来不讨喜
    2020-12-01 12:18

    Check out this - it's an implementation of exactly what you're asking: multi_key_dict(ionary)

    https://pypi.python.org/pypi/multi_key_dict (sources at https://github.com/formiaczek/python_data_structures/tree/master/multi_key_dict)

    (on Unix platforms it possibly comes as a package and you can try to install it with something like:

    sudo apt-get install python-multi-key-dict
    

    for Debian, or an equivalent for your distribution)

    You can use different types for keys but also keys of the same type. Also you can iterate over items using key types of your choice, e.g.:

    m = multi_key_dict()
    m['aa', 12] = 12
    m['bb', 1] = 'cc and 1'
    m['cc', 13] = 'something else'
    
    print m['aa']   # will print '12'
    print m[12]     # will also print '12'
    
    # but also:
    for key, value in m.iteritems(int):
        print key, ':', value
    # will print:1
    # 1 : cc and 1
    # 12 : 12
    # 13 : something else
    
    # and iterating by string keys:
    for key, value in m.iteritems(str):
        print key, ':', value
    # will print:
    # aa : 12
    # cc : something else
    # bb : cc and 1
    
    m[12] = 20 # now update the value
    print m[12]   # will print '20' (updated value)
    print m['aa']   # will also print '20' (it maps to the same element)
    

    There is no limit to number of keys, so code like:

    m['a', 3, 5, 'bb', 33] = 'something' 
    

    is valid, and either of keys can be used to refer to so-created value (either to read / write or delete it).

    Edit: From version 2.0 it should also work with python3.

提交回复
热议问题