user3674231
user3674231

Reputation:

Adding dictionary values to a list?

I have the following:

 list_of_values = []    
 x = { 'key1': 1, 'key2': 2, 'key3': 3 }

How can I iterate through the dictionary and append one of those values into that list? What if I only want to append the value of 'key2'.

Upvotes: 3

Views: 23554

Answers (3)

MSeifert
MSeifert

Reputation: 152637

If you really want to iterate over the dictionary I would suggest using list comprehensions and thereby creating a new list and inserting 'key2' :

list_of_values = [x[key] for key in x if key == 'key2']

because that can be easily extended to search for multiple keywords:

keys_to_add = ['key2'] # Add the other keys to that list.
list_of_values  = [x[key] for key in x if key in keys_to_add]

That has the simple advantage that you create your result in one step and don't need to append multiple times. After you are finished iterating over the dictionary you can append the list, just to make it interesting, you can do it without append by just adding the new list to the older one:

list_of_values += [x[key] for key in x if key in keys_to_add]

Notice how I add them in-place with += which is exactly equivalent to calling list_of_values.append(...).

Upvotes: 1

James
James

Reputation: 2834

list_of_values = []    
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
list_of_values.append(x['key2'])

Upvotes: 0

Colin Schoen
Colin Schoen

Reputation: 2592

If you only want to append a specific set of values you don't need to iterate through the dictionary can simply add it to the list

list_of_values.append(x["key2"])

However, if you insist on iterating through the dictionary you can iterate through the key value pairs:

for key, value in x.items():
   if key == "key2":
      list_of_values.append(value)

Upvotes: 4

Related Questions