Python Forum

Full Version: Get New List Based on Dictionary Key
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to Python. If I have a list indicate the order for a new list with the key in a dictionary, how could I get the new list with the values in the dictionary.

For instance:

l = ['a','b','a','c','b']
D = {'a':[3,2],'b':[4,5],'c':[1]}

How can I get a new list as:
L = [3,4,2,1,5]


A lot of thanks!
What have you tried? We're not big on writing code for people, but we're big on helping people with code they've written.
Here is my code. It gives me the wanted list, but the two "for" loops is a little redundant. I'm wondering if there is simpler way to code it out.

l = ['a','b','a','c','b']
D = {'a':[3,2],'b':[4,5],'c':[1]}


L = []

for i in range(len(l)):
    for k in D:
        if l[i] == k:
            L.append(D[k][0])
            D[k].remove(D[k][0])
Thanks!
something like
my_list= ['a','b','a','c','b']
my_dict = {'a':[3,2],'b':[4,5],'c':[1]}
result = [my_dict[key].pop(0) for key in my_list]
print(result)
but it assumes all elements in my_list are present in my_dict.keys and there are enough elements in the respective list in the dict.
Otherwise
my_list= ['a','b','a','c','b']
my_dict = {'a':[3],'b':[4,5],'c':[1]}
result = []
for key in my_list:
    try:
        result.append(my_dict[key].pop(0))
    except (KeyError, IndexError):
        continue
print(result) 
Awesome, thanks!