The dict.keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.,In this method, we will iterate over each key using the dict.keys() function and append them to a new list named as a list.,Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal. ,The itemgetter from the operator module returns a callable object that fetches an item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and then typecasted to list.
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])
Using a list comprehension:
>>> [dct[k]
for k in lst
]
[5, 3, 3, 3, 3]
Using map
:
>>> [ * map(dct.get, lst)]
[5, 3, 3, 3, 3]
You can use a list comprehension for this:
lstval = [dct.get(k, your_fav_default) for k in lst]
You can iterate keys from your list using map
function:
lstval = list(map(dct.get, lst))
Or if you prefer list comprehension:
lstval = [dct[key] for key in lst ]
lstval = [d[x] for x in lst ]
I would use a list comprehension:
listval = [dict.get(key, 0) for key in lst]
Do not use a dict
as variable name, as it was built in.
>>> d = {
'a': 3,
'b': 3,
'c': 5,
'd': 3
} >>>
lst = ['c', 'd', 'a', 'b', 'd'] >>>
map(lambda x: d.get(x, None), lst)[5, 3, 3, 3, 3]
December 26, 2021December 26, 2021
Dictionary comprehension syntax:
def foo(somelist):
return {
x[0]: x
for x in somelist
}
Simple example code function that will return the name of a key, and the value will be the original value.
def foo(somelist):
return {
x[0]: x
for x in somelist
}
list1 = ["Hello", "World"]
print(foo(list1))
OR
def foo(keyfunc, values):
return dict((keyfunc(v), v) for v in values)
print(foo(lambda a: a[0], ["hello", "world"]))
OSCC · Python, List, Dictionary · Nov 2, 2020
def map_dictionary(itr, fn):
return dict(zip(itr, map(fn, itr)))
map_dictionary([1, 2, 3], lambda x: x * x) # {
1: 1,
2: 4,
3: 9
}
DictionaryKeys (last edited 2022-01-21 13:47:38 by eriky)
1 # retrieve the value for a particular key 2 value = d[key]
1 def lookup(d, key): 2 '' 'dictionary lookup is done in three steps: 3 1. A hash value of the key is computed using a hash function. 4 5 2. The hash value addresses a location in d.data which is 6 supposed to be an array of "buckets" or "collision lists" 7 which contain the(key, value) pairs. 8 9 3. The collision list addressed by the hash value is searched 10 sequentially until a pair is found with pair[0] == key.The 11 return value of the lookup is then pair[1]. 12 '' ' 13 h = hash(key) # step 1 14 cl = d.data[h] # step 2 15 for pair in cl: # step 3 16 if key == pair[0]: 17 return pair[1] 18 else: 19 raise KeyError, "Key %s not found." % key
1 # retrieve the value for a particular key 2 value = d[key]
1 def lookup(d, key): 2 '' 'dictionary lookup is done in three steps: 3 1. A hash value of the key is computed using a hash function. 4 5 2. The hash value addresses a location in d.data which is 6 supposed to be an array of "buckets" or "collision lists" 7 which contain the(key, value) pairs. 8 9 3. The collision list addressed by the hash value is searched 10 sequentially until a pair is found with pair[0] == key.The 11 return value of the lookup is then pair[1]. 12 '' ' 13 h = hash(key) # step 1 14 cl = d.data[h] # step 2 15 for pair in cl: # step 3 16 if key == pair[0]: 17 return pair[1] 18 else: 19 raise KeyError, "Key %s not found." % key
For such a lookup algorithm to work correctly, the hash functions provided must guarantee that if two keys produce different hash values then the two key objects are not equivalent, that is,
for all i1, i2, if hash(i1) != hash(i2), then i1 != i2
Note that this function meets the requirements of a hash function - every time two keys have different hash values, they represent different objects. (This is trivially true because no keys have different hash values - they all have the value 1.) But this is a bad hash function because it means that all (key, value) pairs will be placed in a single list, and so each lookup will require searching this entire list. Thus a (very) desirable property of a hash function is that if two keys produce the same hash values, then the key objects are equivalent, that is,
for all i1, i2, if hash(i1) == hash(i2), then i1 == i2
1 >>> l = [1, 2]
2 >>> d = {}
3 >>> d[l] = 42
4 >>> l.append(3)
5 >>> d[l]
6 Traceback (most recent call last):
7 File "<interactive input>", line 1, in ?
8 KeyError: [1, 2, 3]
9 >>> d[[1, 2]]
10 Traceback (most recent call last):
11 File "<interactive input>", line 1, in ?
12 KeyError: [1, 2]
1 def hash(obj):
2
return 1
1 >>> l = [1, 2]
2 >>> d = {}
3 >>> d[l] = 42
4 >>> l.append(3)
5 >>> d[l]
6 Traceback (most recent call last):
7 File "<interactive input>", line 1, in ?
8 KeyError: [1, 2, 3]
9 >>> d[[1, 2]]
10 Traceback (most recent call last):
11 File "<interactive input>", line 1, in ?
12 KeyError: [1, 2]
The most concise but least readable way to get the list of values from the list of dictionary keys is to use the expression list(map(d.get, keys)) that first applies the d.get(key) function for each key to get an iterable of associated values—and convert everything to a list using the built-in list() function. ,To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys] that iterates over each key in the list of keys and puts the associated value d[key] into the newly-created list.,To get the list of values from a list of keys, you can also iterate over all keys in a simple for loop. The loop body simply consists of a list.append() statement that fills the initially empty list with the associated dictionary values obtained via d[key]. ,This is the most common form used by beginners who are not yet familiar with list comprehension. However, although it’s not the most concise solution, I’d still consider it Pythonic due to its readability and simplicity.
Here’s a minimal example:
# Input: d = { 'alice': 18, 'bob': 24, 'carl': 32 } keys = ['carl', 'bob'] # Output: result = [32, 24]
To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys]
that iterates over each key in the list of keys and puts the associated value d[key]
into the newly-created list.
d = {
'alice': 18,
'bob': 24,
'carl': 32
}
keys = ['carl', 'bob']
result = [d[key]
for key in keys
]
print(result)
#[32, 24]
However, you should know that if the key cannot be found, Python will raise a KeyError:
d = {
'alice': 18,
'bob': 24,
'carl': 32
}
keys = ['carl', 'bob', 'guido']
result = [d[key]
for key in keys
]
print(result)
To fix this without using a clunky try/except statement, simply end the list comprehension statement with a checking mechanism as an if
clause:
d = {
'alice': 18,
'bob': 24,
'carl': 32
}
keys = ['carl', 'bob', 'guido']
result = [d[key]
for key in keys
if key in d
]
print(result)
#[32, 24]
To get the list of values from a list of keys, you can also iterate over all keys in a simple for loop. The loop body simply consists of a list.append()
statement that fills the initially empty list with the associated dictionary values obtained via d[key]
.
d = {
'alice': 18,
'bob': 24,
'carl': 32
}
keys = ['carl', 'bob']
result = []
for key in keys:
result.append(d[key])
print(result)
#[32, 24]