Want to reduce steps of an operation with dictionaries

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Oct 25 07:21:23 CEST 2006

pretoriano_2001 at hotmail.com writes:

> I have next dictionaries:
> a={'a':0, 'b':1, 'c':2, 'd':3}
> b={'a':0, 'c':1, 'd':2, 'e':3}
> I want to put in a new dictionary named c all the keys that are in b
> and re-sequence the values. The result I want is:
> c={'a':0, 'c':1, 'd':2}

Okay, it seems that what you mean isn't what most of us understand by
"re-sequence". I'm not sure what transformation you want to occur.

The result you specify doesn't match your description, "a new
dictionary named c all the keys that are in b and re-sequence the
values", because the result you show doesn't have "all the keys that
are in b".

This gets a dictionary with the keys you want:

    >>> a = {'a':0, 'b':1, 'c':2, 'd':3}
    >>> b = {'a':0, 'c':1, 'd':2, 'e':3}
    >>> c = dict([(k,None)
    ...     for k in a if k in b])
    >>> print c
    {'a': None, 'c': None, 'd': None}

though I don't understand what values you want in the dict.

> How can I do this with one line of instruction?

Why one line?

As a general piece of advice, try writing dumb, obvious code that
actually does the transformation you want, and then let us see
that. Don't try to compress things into fewer lines unless that
actually makes it clearer to read.

> I attempted the next but the output is not the expected:
> c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)])

"if b.has_key(k)" can be replaced with "if k in b", as above.

> erroneously (for me) gets:
> {'a': 0, 'c': 2, 'd': 3}

Perhaps if you could write it as a series of for loops, or some other
more obvious algorithm, we could understand what you actually want.

 \     "What if the Hokey Pokey IS what it's all about?"  -- Anonymous |
  `\                                                                   |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list