[Tutor] advice: making dictionary from two lists?
Roeland Rengelink
r.b.rigilink@chello.nl
Wed, 16 May 2001 21:28:16 +0200
Lance E Sloan wrote:
>
> I've got a couple lists, one is of labels and the other is values.
> They have a one-to-one correspondence. Currently, I'm using this
> method to make them into a dictionary:
>
> labels = ('name', 'age', 'salary')
> values = ('Monty', 42, 5)
>
> # make a dictionary from two lists/tuples
> theDict = {} # or whatever you want to call it
> for (key, value) in map(None, labels, values):
> theDict[key] = value
>
> This works fine, but I just wondered if there was a better (or
> "cooler") way to do this. I wish that dictionaries had an inverse of
> the items() method.
>
Hi Lance,
I can't think of a better way (which doesn't mean that much)
I wouldn't call it cool, and there are plenty reasons not to go here.
But, your wish is my command
from UserDict import UserDict
class genie_dict(UserDict):
def inverse_of_items(self, item_list):
for key, value in item_list:
self.data[key] = value
g = genie_dict()
g.inverse_of_items(zip(('name', 'age', 'salary'), ('Joe', 42, 6000)))
print g
will result in:
{'age': 42, 'name': 'Joe', 'salary': 6000}
On a more serious note:
Your dict looks suspiciously like an employee record, which might
indicate
an EmployeeRecord class
Hope this helps,
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"