Showing posts with label dictionary. Show all posts
Showing posts with label dictionary. Show all posts

Wednesday, May 27, 2020

How to filter a list of dictionaries in python

# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}, {'id':3, "name":"bye!"}]

# This is the list, filtered by the 'name' key
# returns a list that contains one element -- the dictionary with id == 1
filteredlist = list(filter(lambda d: d['name'] in ['import'], list_of_dictionaries))


# This is the list, filtered by the 'name' key
# returns a list that contains two dictionaries
filteredlist = list(filter(lambda d: d['name'] in ['import','python'], list_of_dictionaries))


# understanding the filter function
# https://docs.python.org/3/library/functions.html#filter

# understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions

Tuesday, May 19, 2020

How to sort a list of dictionaries in python


# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}]

# This is the list, sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'])

# This is the list, reverse sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'], reverse=True)

#shortcut to learn more about the sorted function
# https://docs.python.org/3/howto/sorting.html

#understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions



Tuesday, October 27, 2015

How to convert a string to a dictionary

string_to_dictionary
In [1]:
import ast
In [2]:
#this is a string representation of a dictionary.
string = '{"a":"apple","b":"banana","c":"chips"}'
In [3]:
#note that the key returns an error because it is not a dictionary
string['a']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e9bc6d56e007> in <module>()
      1 #note that the key returns an error because it is not a dictionary
----> 2 string['a']

TypeError: string indices must be integers, not str
In [4]:
#This evaluates the string representation into a dictionary
d = ast.literal_eval(string)
In [5]:
d
Out[5]:
{'a': 'apple', 'b': 'banana', 'c': 'chips'}
In [6]:
#The key now returns the value
d['a']
Out[6]:
'apple'