Want to reduce steps of an operation with dictionaries

Michael Naunton mmn at news.bellatlantic.net
Thu Oct 26 23:17:44 EDT 2006


It does not look nice at all, mainly because you are asking either asking the 
question upside down, or not providing enough information.

If a and b are of vastly different sizes, say so.  Otherwise, think about your
algorithm, and realize you are asking for things in b if they exist in a:

> dict( [ i for i in b.items() if i[0] in a ] )
{'a': 0, 'c': 1, 'd': 2}

- another mike.

pretoriano_2001 at hotmail.com <pretoriano_2001 at hotmail.com> wrote:
> Mike:
> Many thanks for your solution. It looks really nice.
>
>
>
> Mike Erickson wrote:
>> * pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) wrote:
>> > Hello:
>> > 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}
>> > How can I do this with one line of instruction?
>> >
>> > 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)])
>> > erroneously (for me) gets:
>> > {'a': 0, 'c': 2, 'd': 3}
>>
>> I am not 100% I understand your questions, but k,v are being pulled from
>> a, try:
>>
>> c=dict([(k,b[k]) for v,k in enumerate(a) if b.has_key(k)])
>> 
>> mike
>



More information about the Python-list mailing list