Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.


1 Answers

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)
like image 83
Colin Schoen Avatar answered May 18 '26 20:05

Colin Schoen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!