2

Lets say i have a dictionary:

favorittForfattere={'Per':'Christie','Kari':'Ibsen', \
 'Liv':'Rowling','Ola':'Ibsen', \
'Anne':'Allende', 'Jens':'Christie'}

With this dictionary i want to create a function where i get the keys and values from that dictionary, and then append them in to a new dictionary which gets created during the function. the values of the previous dictionary will be keys in the new dictionary. the keys from the previous dictionary will be values in the new dictionary.

The expeted outcome would be this

{'Christie': ['Per', 'Jens'], 'Ibsen': ['Kari', 'Ola'], 'Rowling': ['Liv'], 'Allende': ['Anne']}

This is my code so far

def fans(favorittForfattere):
    nyFortegnelse = {}
    for keys, values in favorittForfattere.items():
        nyFortegnelse.update({values:keys})
    print(nyFortegnelse)

How would i solve this problem?

This is the whole code snip so it makes sence

favorittForfattere={'Per':'Christie','Kari':'Ibsen', \
 'Liv':'Rowling','Ola':'Ibsen', \
'Anne':'Allende', 'Jens':'Christie'}

def fans(favorittForfattere):
    nyFortegnelse = {}
    for keys, values in favorittForfattere.items():
        nyFortegnelse.update({values:keys})
    print(nyFortegnelse)

fans(favorittForfattere)

Roald Andre Kvarv
  • 187
  • 1
  • 3
  • 21

3 Answers3

3

Using dict.setdefault with value as list.

Ex:

favorittForfattere={'Per':'Christie','Kari':'Ibsen', 'Liv':'Rowling','Ola':'Ibsen', 'Anne':'Allende', 'Jens':'Christie'}

def fans(favorittForfattere):
    nyFortegnelse = {}
    for key, value in favorittForfattere.items():
        nyFortegnelse.setdefault(value, []).append(key)
    print(nyFortegnelse)

fans(favorittForfattere)

Output:

{'Allende': ['Anne'],
 'Christie': ['Per', 'Jens'],
 'Ibsen': ['Kari', 'Ola'],
 'Rowling': ['Liv']}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

you can use this code:

favorittForfattere={'Per':'Christie','Kari':'Ibsen','Liv':'Rowling','Ola':'Ibsen','Anne':'Allende', 'Jens':'Christie'}
dictionary={}
for i in favorittForfattere:
    if favorittForfattere[i] not in dictionary:
        dictionary[favorittForfattere[i]]=[]
    dictionary[favorittForfattere[i]].append(i)

output:

{'Christie': ['Per', 'Jens'],
 'Ibsen': ['Kari', 'Ola'],
 'Rowling': ['Liv'],
 'Allende': ['Anne']}
Benyamin Karimi
  • 133
  • 1
  • 1
  • 9
0

Something like this?

def fans(favorittForfattere):
    nyFortegnelse = {}
    for k, v in favorittForfattere.items():
        nyFortegnelse[v] = nyFortegnelse.get(v, [])
        nyFortegnelse[v].append(k)
    return nyFortegnelse
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Tobias
  • 12
  • 4