Want to reduce steps of an operation with dictionaries

Steve Holden steve at holdenweb.com
Tue Oct 24 23:45:51 EDT 2006


Carl Banks wrote:
> Steve Holden wrote:
> 
>>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?
>>>
>>
>>You can't. Dictionaries aren't ordered collections.
>>
>>
>>>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}
>>>
>>>Thanks for your help.
>>
>>In Python {'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3}
> 
> 
> Careful there, chief.  The Python interpreter disagrees:
> 
> 
>>>>{'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3}
> 
> False
> 
> I inferred that by "re-sequencing", the OP meant the keys in the new
> dict were to be associated with a new range of integer values (probably
> specifically the key's index in a sorted list of keys).  It was an
> unfortunate choice of words, as sequencing has a pretty specific
> meaning in Python.
> 
> 
Thanks: my bad.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list