-1

Hi want to understand how to make this code shorter using dictionary comprehension:

for e in list_of_tuples:
            tmp = mydict.copy()
            tmp[e[0]] = tmp[e[1]]
                if someFunction(tmp):
                    mydict = tmp

I would like to pass a dictionary comprehension to someFunction instead of relying on a temporary dictionary whose values are changed in the loop. Is it possible?

linello
  • 8,451
  • 18
  • 63
  • 109
  • does this code works? can you explain what are you trying to do? – Elisha Apr 24 '14 at 14:32
  • 3
    You are using `tmp` for **two** things: to pass to `someFunction` and to then bind `mydict` to it. What is the binding for? – Martijn Pieters Apr 24 '14 at 14:37
  • Sorry, realized that I misunderstood your question. – msvalkon Apr 24 '14 at 14:45
  • I think I see what you want here; you want to build `mydict` from a dict comprehension, but only with keys that leave the *whole* dictionary in a consistent state. That's probably not going to work then, as `someFunction` wants to have access to the *partially* constructed dictionary, which is not available in a dict comprehension. – Martijn Pieters Apr 24 '14 at 15:16

1 Answers1

0

This answer assumes that someFunction does not alter the dictionary

The dictionary passed to someFunction is still going to be a basic copy of mydict, but this is the only way I can think of answering the question with comprehension.

for e in list_of_tuples:
    if someFunction({key: val if key != e[0] else mydict[e[1]] for key,val in mydict }):
        mydict[e[0]] = mydict[e[1]]

However the faster/ easier way would be to just make a temp variable for mydict[e[0]], and change it back after if someFunction fails. Also having extra lines isn't always a bad thing. It can usually help readability, solving bugs and maintenance.. especially for newer programmers.

for e in list_of_tuples:
    temp = mydict[e[0]]
    mydict[e[0]] = mydict[e[1]]
    if not someFunction(mydict):
        mydict[e[0]] = temp
flakes
  • 21,558
  • 8
  • 41
  • 88
  • The dict comprehension is overkill here if `e[0]` is always a string; `dict(mydict, **{e[0]: e[1]})` would accomplish the same. – Martijn Pieters Apr 24 '14 at 15:18
  • @Martijn Pieters, I agree completely. But if we don't know the data type of the keys, how else could it be created as a one liner? – flakes Apr 24 '14 at 15:32
  • what is this ** syntax in this context? – Jasper Apr 24 '14 at 17:30
  • @Jasper `**` is used to expand maps/dictionaries usually for keyword arguments.. `*` is used for lists. ie `*(a, b)` -> `a,b`, `**{'a':1,'b':2}` -> `a = 1, b = 2` Read up here for its use in `dict` https://docs.python.org/2/library/stdtypes.html#mapping-types-dict – flakes Apr 24 '14 at 18:56