简体   繁体   中英

Swap around key and value (containing a list) within a Python dictionary

I have a reference dictionary with subjects and page numbers like so:

reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] }

I need help writing a function that inverts the reference. That is, returns a dictionary with page numbers as keys, each with an associated list of subjects. For example, swap(reference) run on the above example should return

{ 1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 
9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths'] }

You can use a defaultdict :

from collections import defaultdict

d = defaultdict(list)
reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] }
for a, b in reference.items():   
    for i in b:    
        d[i].append(a)
print(dict(d))

Output:

{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}

Without importing from collections :

d = {}
for a, b in reference.items():
    for i in b:
        if i in d:
           d[i].append(a)
        else:
           d[i] = [a]

Output:

{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
reference = {'maths': [3, 24], 'physics': [4, 9, 12], 'chemistry': [1, 3, 15]} table = [] newReference = {} for key in reference: values = reference[key] for value in values: table.append((value, key)) for x in table: if x[0] in newReference.keys(): newReference[x[0]] = newReference[x[0]] + [x[1]] else: newReference[x[0]] = [x[1]] print(newReference)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM