Search code examples
pythonpython-3.xlistdictionarydefaultdict

Creating Python dictionaries with keys based on items in list of list


I'm creating a dictionary where if the key has an 'R' then one list, otherwise it goes in the list for 'E'. My code so far:

d1 = {'SSW 540': ['E', 'SYEN'], 'SSW 564': ['R', 'SFEN'], 'SSW 567': ['R', 'SFEN'], 'CS 501': ['E', 'SFEN']}

rlist = []
elist = []

for k, v in d1.items():
    if v[0] == 'R':
        rlist.append([v[1], k])
    elif v[0] == 'E':
        elist.append([v[1], k])

Output is:

rlist = [['SFEN', 'SSW 564'], ['SFEN', 'SSW 567']]
elist = [['SYEN', 'SSW 540'], ['SFEN', 'CS 501']]

How could I create two dictionaries, call them rdict and edict where:

rdict = {'SFEN': ['SSW 564','SSW 567']}
edict = {'SYEN': ['SSW 540'], 'SFEN': ['CS 501']}

There could be more values than just 'SYEN' and 'SFEN' so it needs to be any particular first element in the list.

If I try something like:

mlist = {}

for list in rlist:
    if list[0] in rlist:
        mlist.append(list[1])
    else:
        mlist[list[0]].append(list[1])

I get KeyError: 'SFEN'. Could I use defaultdict for this?


Solution

  • There is a way to create m_dict from d1 directly.

    d1 = {
        'SSW 540': ['E', 'SYEN'],
        'SSW 564': ['R', 'SFEN'],
        'SSW 567': ['R', 'SFEN'],
        'CS 501': ['E', 'SFEN'],
    }
    
    m_dict = {}
    for value, (category, key) in d1.items():
        m_dict.setdefault(category, {}).setdefault(key, []).append(value)
    
    print(m_dict)
    

    output:

    {'E': {'SYEN': ['SSW 540'], 'SFEN': ['CS 501']}, 'R': {'SFEN': ['SSW 564', 'SSW 567']}}
    

    Explanation:

    • dict.setdefault(key, default)
      • It sets at key by default if key doesn't exist.
      • And return always value of key itself.
    • for value, (category, key) in d1.items():
      • You can unpack fixed-length tuple, list, or other sequences.
      • So it is equivalent with:
    for value, tuple_ in d1.items():
        category, key = tuple_