1

I've got the following two dictionaries in python which I need to transform in a way to get the third dictionary

    matrikelnummer_zu_note = { 35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4 }
    note_zahl_zu_string = { 1: "summa cum laude", 2: "magna cum laude", 3: "cum laude", 4: "rite", 5: "non probatum" }

    {60103513: 'cum laude', 10981179: 'magna cum laude', 18637724: 'rite', 35135135: 'non probatum'}

So I need to get the values of the first dictionary and replace them with the values linked with the corresponding keys in the second dictionary.

I could solve this doing a simple loop like this:

def transform_dict(d1, d2): 
    for x in d1.keys():
        d1[x]=d2[d1[x]]
    return d1

But our prof wants us to solve the problem using the map() function and lambda-expressions.

Now I've started by trying to "build" my solution around a lambda and a map function this way:

def transform_dict(d1, d2):
    liste = list(d1.values())
    liste.sort()
    list(map(lambda elem_from_list,dictionary: dictionary[elem_from_list],liste,d2 ))

But I get an error in the last line saying TypeError: 'int' object is not subscriptable

I'd really appreciate any help solving this problem.

Thanks a lot in advance

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Druckermann
  • 681
  • 2
  • 11
  • 31

2 Answers2

3

You can map over the dictionary's items which are key-value pairs, and then for each value, use it as key to get value from another dictionary:

dict(map(lambda item: 
  (item[0], note_zahl_zu_string.get(item[1], item[1])), 
  matrikelnummer_zu_note.items()))

#{10981179: 'magna cum laude',
# 18637724: 'rite',
# 35135135: 'non probatum',
# 60103513: 'cum laude'}
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 1
    @2ps Thanks for the edit. But this raises an error in python 3. You can't unpack tuple in lambda in python 3 anymore. See [here](http://stackoverflow.com/questions/11328312/python-lambda-does-not-accept-tuple-argument) – Psidom Jan 19 '17 at 20:02
2

When you iterate (i.e. map) over a dictionary, it maps over the keys. This explains your error, since your lambda has two arguments, and the second receives keys from note_zahl_zu_string.

So, something like this should be enough:

>>> d1 = matrikelnummer_zu_note
>>> d2 = note_zahl_zu_string
>>> dict(map(lambda k1: (k1, d2[d1[k1]]), d1))
{60103513: 'cum laude', 10981179: 'magna cum laude', 18637724: 'rite', 35135135: 'non probatum'}
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172