how to get a list which is a value of a dictionary by a value from the list?

  • Last Update :
  • Techknowledgy :

Last Updated : 01 Dec, 2021,GATE CS 2021 Syllabus

Syntax:

list(dictionary.values())

Output:

['java', 'python', 'statistics', 'cpp']

Syntax:

[dictionary[i]
   for i in dictionary
]

Suggestion : 2

dict.values returns a view of the dictionary's values, so you have to wrap it in list:

list(d.values())

You can use * operator to unpack dict_values:

>>> d = {
      1: "a",
      2: "b"
   } >>>
   [ * d.values()]
   ['a', 'b']

or list object

>>> d = {
      1: "a",
      2: "b"
   } >>>
   list(d.values())['a', 'b']

[*L] vs. [].extend(L) vs. list(L)

small_ds = {
   x: str(x + 42) for x in range(10)
}
small_df = {
   x: float(x + 42) for x in range(10)
}

print('Small Dict(str)') %
   timeit[ * small_ds.values()] %
   timeit[].extend(small_ds.values()) %
   timeit list(small_ds.values())

print('Small Dict(float)') %
   timeit[ * small_df.values()] %
   timeit[].extend(small_df.values()) %
   timeit list(small_df.values())

big_ds = {
   x: str(x + 42) for x in range(1000000)
}
big_df = {
   x: float(x + 42) for x in range(1000000)
}

print('Big Dict(str)') %
   timeit[ * big_ds.values()] %
   timeit[].extend(big_ds.values()) %
   timeit list(big_ds.values())

print('Big Dict(float)') %
   timeit[ * big_df.values()] %
   timeit[].extend(big_df.values()) %
   timeit list(big_df.values())
Small Dict(str)
256 ns± 3.37 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)
338 ns± 0.807 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)
336 ns± 1.9 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns± 0.297 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)
343 ns± 15.2 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)
336 ns± 0.68 ns per loop(mean± std.dev.of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms± 142 µs per loop(mean± std.dev.of 7 runs, 100 loops each)
16.5 ms± 338 µs per loop(mean± std.dev.of 7 runs, 100 loops each)
16.2 ms± 19.7 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms± 41 µs per loop(mean± std.dev.of 7 runs, 100 loops each)
13.1 ms± 919 µs per loop(mean± std.dev.of 7 runs, 100 loops each)
12.8 ms± 578 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name Version Build
ipython 7.5 .0 py37h24bf2e0_0

Follow the below example --

songs = [{
      "title": "happy birthday",
      "playcount": 4
   },
   {
      "title": "AC/DC",
      "playcount": 2
   },
   {
      "title": "Billie Jean",
      "playcount": 6
   },
   {
      "title": "Human Touch",
      "playcount": 3
   }
]

print("====================")
print(f 'Songs --> {songs} \n')
title = list(map(lambda x: x['title'], songs))
print(f 'Print Title --> {title}')

playcount = list(map(lambda x: x['playcount'], songs))
print(f 'Print Playcount --> {playcount}')
print(f 'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
   print(sorted(list(map(lambda x: x['playcount'], songs))))

Most straightforward way is to use a comprehension by iterating over list_of_keys. If list_of_keys includes keys that are not keys of d, .get() method may be used to return a default value (None by default but can be changed).

res = [d[k]
   for k in list_of_keys
]
# or
res = [d.get(k) for k in list_of_keys]

As often the case, there's a method built into Python that can get the values under keys: itemgetter() from the built-in operator module.

from operator
import itemgetter
res = list(itemgetter( * list_of_keys)(d))

Demonstration:

d = {
   'a': 2,
   'b': 4,
   'c': 7
}
list_of_keys = ['a', 'c']
print([d.get(k) for k in list_of_keys])
print(list(itemgetter( * list_of_keys)(d)))
#[2, 7]
#[2, 7]
out: dict_values([{
   1: a,
   2: b
}])

in: str(dict.values())[14: -3]
out: 1: a, 2: b

Suggestion : 3

Another way to find the values is by using map() and lambda functions. Lambda takes the key (whose corresponding values is to be found) and name of the iterable as arguments. It returns the corresponding values of the given key to the map() function. list() constructor returns the list of comma-separated values.,This method uses a list comprehension technique to find the list of values. It takes a key as input and returns a list containing the corresponding value for each occurrence of the key in each dictionary in the list using for loop. This method is more elegant and pythonic than others.,This method is very simple and uses Brute Force Approach. It takes an empty list to add values one by one because of which the Space Complexity of this program increases. for loop is used to iterate over the elements of the list books and values matching the given key is added to the empty list using append() function.,In this article, we learned to find the list of values from a given list of dictionaries by using several built-in functions such as append(), map(), lambda, operator and functools module etc and different examples to find the values on the basis of the given key. The best method is the list comprehension technique. You can even use generators in Python to perform this operation.

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values. For example,

list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

Dictionaries are Python's other built-in data type and it is also known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Data inside a dictionary can be of any type say, integer, string or a float value, etc.. A dictionary can be defined using any variable name and then assigning different key-value pairs in curly braces. For example,

dict1 = {
   "A": 1,
   "B": 2,
   "C": 3
}
dict2 = {
   "Name": "Jeffery",
   1: [2, 4, 3]
}
dict3 = {
   1: "first",
   2: "second"
}

This method uses a list comprehension technique to find the list of values. It takes a key as input and returns a list containing the corresponding value for each occurrence of the key in each dictionary in the list using for loop. This method is more elegant and pythonic than others.

#list of dictionaries
books = [{
      "title": "Pride and Prejudice ",
      "author": "Jane Austen"
   },
   {
      "title": "David Copperfield",
      "author": "Charles Dickens"
   },
   {
      "title": "Wuthering Heights",
      "author": "Emily Brontë"
   },
   {
      "title": "War and Peace ",
      "author": "Tolstoy"
   }
]

#define a key
a_key = "title"

list_of_values = [a_dict[a_key]
   for a_dict in books
]

print(list_of_values)

This method uses the combination of itertools and the operator module in python to find the values. operator.itemgetter() function stores all the values associated with the given key in a variable. This variable and map are passed as arguments to functools.partial(). It is a higher-order function that takes a function as input like map and binds multiple arguments to the same function. Python 3 uses list() constructor to return a list since map returns an iterator.

#list of dictionary
books = [{
      "title": "Pride and Prejudice ",
      "author": "Jane Austen"
   },
   {
      "title": "David Copperfield",
      "author": "Charles Dickens"
   },
   {
      "title": "Wuthering Heights",
      "author": "Emily Brontë"
   },
   {
      "title": "War and Peace ",
      "author": "Tolstoy"
   }
]

import operator, functools

get_value = operator.itemgetter('title')
list_of_values = functools.partial(map, get_value)
print(list(list_of_values(books)))

This method is very simple and uses Brute Force Approach. It takes an empty list to add values one by one because of which the Space Complexity of this program increases. for loop is used to iterate over the elements of the list books and values matching the given key is added to the empty list using append() function.

#list of dictionary
books = [{
      "title": "Pride and Prejudice ",
      "author": "Jane Austen"
   },
   {
      "title": "David Copperfield",
      "author": "Charles Dickens"
   },
   {
      "title": "Wuthering Heights",
      "author": "Emily Brontë"
   },
   {
      "title": "War and Peace ",
      "author": "Tolstoy"
   }
]

#empty list
list_of_values = ['']
j = 0
for i in books:
   if j == 0:
   list_of_values[0] = (i['title'])
else:
   list_of_values.append(i['title'])
j += 1
print(list_of_values)

Suggestion : 4

JavaScript seems to be disabled in your browser. You must have JavaScript enabled in your browser to utilize the functionality of this website.

thelist = [{
      'value': 'apple',
      'blah': 2
   },
   {
      'value': 'banana',
      'blah': 3
   },
   {
      'value': 'cars',
      'blah': 4
   }
]

thisvalues = [d['value']
   for d in thelist
   if 'value' in d
]
print(thisvalues)
['apple', 'banana', 'cars']

Suggestion : 5

December 24, 2021December 24, 2021

To get the value of a list of dictionaries first we have to access the dictionary using indexing.

list_data[index][key]

Simple example code.

data = [{
      101: 'Any',
      102: 'Bob'
   },
   {
      103: 'John',
      105: 'Tim'
   }
]

# display data of key 101
print(data[0][101])

# display data of key 105
print(data[1][105])

We can easily access any key:value pair of the dictionary, just pass the index value of the dictionary in square bracket [].

data = [{
      101: 'Any',
      102: 'Bob'
   },
   {
      103: 'John',
      105: 'Tim'
   }
]

print(data[1])

Get all values of the list dictionary

my_dict = [{
      'value': 'apple',
      'blah': 2
   },
   {
      'value': 'banana',
      'blah': 3
   },
   {
      'value': 'cars',
      'blah': 4
   }
]

res = []

for key in my_dict:
   for value in key:
   res.append(key.values())

print(res)

Output:

[dict_values(['apple', 2]), dict_values(['apple', 2]), dict_values(['banana', 3]), dict_values(['banana', 3]), dict_values(['cars', 4]), dict_values(['cars', 4])]

Suggestion : 6

A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair.,To iterate over all key-value pairs in a dictionary, you use a for loop with two variable key and value to unpack each tuple of the list:,A key in the key-value pair must be immutable. In other words, the key cannot be changed, for example, a number, a string, a tuple, etc.,The person dictionary has five key-value pairs that represent the first name, last name, age, favorite colors, and active status.

The following example defines an empty dictionary:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
empty_dict = {}
Code language: Python(python)

To find the type of a dictionary, you use the type() function as follows:

empty_dict = {}

print(type(empty_dict))
Code language: Python(python)

Ouptut:

<class 'dict'>Code language: Python (python)

To access a value associated with a key, you place the key inside square brackets:

dict[key] Code language: Python(python)

The following shows how to get the values associated with the key first_name and last_name in the person dictionary:

person = {
   'first_name': 'John',
   'last_name': 'Doe',
   'age': 25,
   'favorite_colors': ['blue', 'green'],
   'active': True
}
print(person['first_name'])
print(person['last_name']) Code language: Python(python)