Reputation: 9213
I have a list of list, s
, that is the result of querying a database on Fruit, item[0]
is the name of the fruit, item[1]
is the whether or not the fruit has seeds, and item[2]
is whether or not it's edible.
s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]
As my actual list is much bigger, I would like a really easy way to reference/return these values. For example, print my_dict['Apple']['Seeds']
would yield Yes
I think my best option would be to create a dictionary, but am looking for recommendations on if this is a good method and how to do this.
I started writing some code but am not sure how to get the second set of headers in place, so my example uses an index instead.
my_dict = {t[0]:t[1:] for t in s}
print my_dict['Apple'][0]
Upvotes: 0
Views: 65
Reputation: 1400
If the second set of keys never changes, it would be better to define a proper object with fields. This might seem overkill or to verbose, but there is always collections.namedtuple
to help.
namedtuple
creates a new class from a list of field names. That class also supports being initialized by a list. To use your example:
import collections
Fruit = collections.namedtuple('Fruit', ['name', 'seeds', 'edible'])
This way, you can easily create Fruit
objects from a list:
f = Fruit('Apple', True, False)
# Or, if you already have a list with the values
params = ['Apple', True, False]
f = Fruit(*params)
print f.seed
So you can create a list of fruits in a very easy way:
s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]
fruits = [Fruit(*l) for l in s]
You really need to have a dictionary indexed by a certain field, it is not much different:
s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]
fruit_dict = {l[0]: Fruit(*l) for l in s}
print(fruit_dict['Apple'].seeds)
namedtuple
s can be very convenient when transforming lists of values into more easy to use objects (such as when reading a CSV file, which is a case very similar to what you are asking).
Upvotes: 2
Reputation: 16711
import copy
def list_to_dict(lst):
local = copy.copy(lst) # copied lst to local
fruit = [i.pop(0) for i in local] # get fruit names
result = {}
for i in range(len(local)):
result[fruit[i]] = local[i]
return result
This returns the dictionary you want.
Upvotes: 0
Reputation: 2442
fruit_map = {
fruit: {'Seeds': seeds, 'Edible': edible} for fruit, seeds, edible in s}
Upvotes: 5