get a dict from a python list

  • Last Update :
  • Techknowledgy :
1._
my_item = next((item
   for item in my_list
   if item['id'] == my_unique_id), None)

This iterates through the list until it finds the first item matching my_unique_id, then stops. It doesn't store any intermediate lists in memory (by using a generator expression) or require an explicit loop. It sets my_item to None of no object is found. It's approximately the same as

for item in my_list:
   if item['id'] == my_unique_id:
   my_item = item
break
else:
   my_item = None

If you have to do this multiple times, you should recreate a dictionnary indexed by id with your list :

keys = [item['id']
   for item in initial_list
]
new_dict = dict(zip(keys, initial_list))

   >>>
   {
      'yet another id': {
         'id': 'yet another id',
         'value': 901.20000000000005,
         'title': 'last title'
      },
      'an id': {
         'id': 'an id',
         'value': 123.40000000000001,
         'title': 'some value'
      },
      'another id': {
         'id': 'another id',
         'value': 567.79999999999995,
         'title': 'another title'
      }
   }

or in a one-liner way as suggested by agf :

new_dict = dict((item['id'], item) for item in initial_list)

I used this, since my colleagues are probably more able to understand what's going on when I do this compared to some other solutions provided here:

[item
   for item in item_list
   if item['id'] == my_unique_id
][0]

Worked only with iter() for me:

my_item = next(iter(item
   for item in my_list
   if item['id'] == my_unique_id), None)

You can create a simple function for this purpose:

lVals = [{
      'title': 'some value',
      'value': 123.4,
      'id': 'an id'
   },
   {
      'title': 'another title',
      'value': 567.8,
      'id': 'another id'
   },
   {
      'title': 'last title',
      'value': 901.2,
      'id': 'yet another id'
   }
]

def get_by_id(vals, expId): return next(x
   for x in vals
   if x['id'] == expId)

get_by_id(lVals, 'an id') >>>
   {
      'value': 123.4,
      'title': 'some value',
      'id': 'an id'
   }
In[2]: test_list
Out[2]: [{
      'id': 'an id',
      'title': 'some value',
      'value': 123.40000000000001
   },
   {
      'id': 'another id',
      'title': 'another title',
      'value': 567.79999999999995
   },
   {
      'id': 'yet another id',
      'title': 'last title',
      'value': 901.20000000000005
   }
]

In[3]: [d
   for d in test_list
   if d["id"] == "an id"
]
Out[3]: [{
   'id': 'an id',
   'title': 'some value',
   'value': 123.40000000000001
}]

Suggestion : 2

Last Updated : 25 Jul, 2022

1._
Input: {
   1: 'a',
   2: 'b',
   3: 'c'
}
Output: [1, 2, 3]

Input: {
   'A': 'ant',
   'B': 'ball'
}
Output: ['A', 'B']

Output:

dict_keys([1, 2, 3])

Suggestion : 3

If no default value was passed in fromKeys() then default value for keys in dictionary will be None.,Convert List items as keys in dictionary with enumerated value,In this article we will discuss different ways to convert a single or multiple lists to dictionary in Python.,If length of keys list is less than list of values then remaining elements in value list will be skipped.

Suppose we have a list of strings i.e.

# List of strings
listOfStr = ["hello", "at", "test", "this", "here", "now"]

Using dictionary comprehension

''
'
Converting a list to dictionary with list elements as keys in dictionary
All keys will have same value
   ''
' 
dictOfWords = {
   i: 5
   for i in listOfStr
}

hello::5
here::5
this::5
test::5
at::5
now::5

Dictionary contents are,

Dictionary from two Lists
hello::56
here::43
this::97
test::43
at::23
now::102

Suppose we have a list of tuples with two columns in each entry i.e.

# List of tuples
listofTuples = [("Riti", 11), ("Aadi", 12), ("Sam", 13), ("John", 22), ("Lucy", 90)]

Suggestion : 4

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:,Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.,Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).,The list data type has some more methods. Here are all of the methods of list objects:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>>
   fruits.count('apple')
2
   >>>
   fruits.count('tangerine')
0
   >>>
   fruits.index('banana')
3
   >>>
   fruits.index('banana', 4) # Find next banana starting a position 4
6
   >>>
   fruits.reverse() >>>
   fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>>
   fruits.append('grape') >>>
   fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>>
   fruits.sort() >>>
   fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>>
   fruits.pop()
'pear'
>>> stack = [3, 4, 5] >>>
   stack.append(6) >>>
   stack.append(7) >>>
   stack[3, 4, 5, 6, 7] >>>
   stack.pop()
7
   >>>
   stack[3, 4, 5, 6] >>>
   stack.pop()
6
   >>>
   stack.pop()
5
   >>>
   stack[3, 4]
>>> from collections
import deque
   >>>
   queue = deque(["Eric", "John", "Michael"]) >>>
   queue.append("Terry") # Terry arrives >>>
   queue.append("Graham") # Graham arrives >>>
   queue.popleft() # The first to arrive now leaves 'Eric' >>>
   queue.popleft() # The second to arrive now leaves 'John' >>>
   queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
>>> squares = [] >>>
   for x in range(10):
   ...squares.append(x ** 2)
   ...
   >>>
   squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = list(map(lambda x: x ** 2, range(10)))
squares = [x ** 2
   for x in range(10)
]

Suggestion : 5

In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type.,Create a List of Dictionaries in Python,In this tutorial of Python Examples, we learned about list of dictionaries in Python and different operations on the elements of it, with the help of well detailed examples.,In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.

Python Program

myList = [{
      'foo': 12,
      'bar': 14
   },
   {
      'moo': 52,
      'car': 641
   },
   {
      'doo': 6,
      'tar': 84
   }
]

print(myList)

Output

[{
   'foo': 12,
   'bar': 14
}, {
   'moo': 52,
   'car': 641
}, {
   'doo': 6,
   'tar': 84
}]

Suggestion : 6

Dictionary is a collection of key:value pairs. You can get all the keys in the dictionary as a Python List.,dict.keys() returns an iterable of type dict_keys(). You can convert this into a list using list().,In this example, we will create a list and add all the keys of dictionary one by one while iterating through the dictionary keys.,In this example, we will create a Dictionary with some initial values and then get all the keys as a List into a variable.

example.py – Python Program

#initialize dictionary
aDict = {
   'tallest building': 'Burj Khalifa',
   'longest river': 'The Nile',
   'biggest ocean': 'The Pacific Ocean'
}

# get keys as list
keys = list(aDict.keys())

#print keys
print(keys)

Output

['tallest building', 'longest river', 'biggest ocean']