Codees
Codees

Reputation: 7

append lists in dictionary depending on another list python?

I have a dictionary like this with empty list as values

e = {'joe': [], 'craig': [], 'will' : []}

Then with this list below, I want to add the order of the names to the list inside the dictionary corresponding to the key

['craig', 'joe', 'will']

so the expected output would be

{'joe': [2], 'craig': [1], 'will' : [3]}

craig came first, joe came second, will came third

Upvotes: 0

Views: 243

Answers (6)

leeladam
leeladam

Reputation: 1758

What you need is list.index(). See docs here.

e = {'joe': [], 'craig': [], 'will' : []}
names = ['craig', 'joe', 'will']

e['joe'] = names.index('joe')+1

Note 1. You might use for name in names if you want to iterate over all names in list.

Note 2. What do you do if there is a name in your list that is not found as a key in the dictionary?

Note 3. What do you do if the same names occurs more than once in your list?

Note 4. Are you sure you want to serialize your list counting from one (1, 2, 3...) and not counting from zero as Python does? (0, 1, 2...).

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142176

You can use dict.update:

d = {'joe': [], 'craig': [], 'will' : []}
n = ['craig', 'joe', 'will']
d.update((k, d[k] + [i]) for i, k in enumerate(n, 1))
# {'craig': [1], 'will': [3], 'joe': [2]}

Upvotes: 0

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

e = {'joe': [], 'craig': [], 'will' : []}
l = ['craig', 'joe', 'will']
for i,v in enumerate(l, 1):
    e[v].append(i)

print e

>>> 
{'will': [3], 'craig': [1], 'joe': [2]}

Upvotes: 0

Danny Staple
Danny Staple

Reputation: 7332

You could use enumerate perhaps? I will assume you've initialised e to the dictionary of empty names. And namelist is the list of names in the order you want.

for name in e.keys:
  e[name].append(namelist.index[name])

Upvotes: 0

fredtantini
fredtantini

Reputation: 16556

You can use the enumerate function:

>>> e = {'joe': [], 'craig': [], 'will' : []}
>>> for i,j in enumerate(['craig', 'joe', 'will']):
...   e[j].append(i+1)
...
>>> e
{'will': [3], 'craig': [1], 'joe': [2]}

Or the index method of list:

>>> e = {'joe': [], 'craig': [], 'will' : []}
>>> l = ['craig', 'joe', 'will']
>>> for i in l:
...   e[i].append(l.index(i)+1)
...
>>> e
{'will': [3], 'craig': [1], 'joe': [2]}

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304215

e = {'joe': [], 'craig': [], 'will' : []}
for i, key in enumerate(['craig', 'joe', 'will'], 1):
    e[key].append(i)

print e

{'will': [3], 'craig': [1], 'joe': [2]}

Upvotes: 3

Related Questions