文章目录
- Ten different ways to convert a Python list to a dictionary
在Python中将列表转换为字典的10种方法 - 1. Converting a List of Tuples to a Dictionary
- 2. Converting Two Lists of the Same Length to a Dictionary
- 3.Converting Two Lists of Different Length to a Dictionary
- 4. Converting a List of Alternative Key, Value Items to a Dictionary
- 5. Converting a List of Dictionaries to a Single Dictionary
- 6. Converting a List to a Dictionary Using ```Enumerate()```
- 7. Converting List Into a Dictionary Using Dictionary Comprehension
- 8. Converting a List to a Dictionary Using ```dict.fromkeys()```
- 9. Converting a Nested List to a Dictionary Using Dictionary Comprehension
- 10. Converting a List to a Dictionary Using ```Counter()```
原文链接: https://medium.com/better-programming/10-ways-to-convert-lists-to-dictionaries-in-python-d2c728d2aeb8
Python Data Structures
Python lists and dictionaries are two data structures in Python used to store data. A Python list is an ordered sequence of objects, whereas dictionaries are unordered. The items in the list can be accessed by an index (based on their position) whereas items in the dictionary can be accessed by keys and not by their position.
Python列表和字典是Python中用于存储数据的两个数据结构。 Python列表是对象的有序序列,而字典是无序的。 列表中的项目可以通过索引(基于它们的位置)来访问,而字典中的项目可以通过键而不是它们的位置来访问。
Let’s see how to convert a Python list to a dictionary.
让我们看看如何将Python列表转换成字典。
Ten different ways to convert a Python list to a dictionary
在Python中将列表转换为字典的10种方法
- Converting a list of tuples to a dictionary
将元组列表转换为字典 - Converting two lists of the same length to a dictionary
将两个相同长度的列表转换为字典 - Converting two lists of different length to a dictionary
将两个不同长度的列表转换为字典 - Converting a list of alternative key, value items to a dictionary
将备用键,值项列表转换为字典 - Converting a list of dictionaries to a single dictionary
将词典列表转换为单个词典 - Converting a list into a dictionary using enumerate()
使用enumerate()
将列表转换成字典 - Converting a list into a dictionary using dictionary comprehension
使用字典推导式将列表转换为字典 - Converting a list to a dictionary using dict.fromkeys()
使用dict.fromkeys()
将列表转换成字典 - Converting a nested list to a dictionary using dictionary comprehension
使用字典推导式将嵌套列表转换为字典 - Converting a list to a dictionary using Counter()
使用Counter()
将列表转换为字典
1. Converting a List of Tuples to a Dictionary
The dict()
constructor builds dictionaries directly from sequences of key-value pairs.
dict()
构造函数直接从键值对序列中构建字典。
l1=[(1,'a'),(2,'b'),
(3,'c'),(4,'d')]
d1=dict(l1)
print (d1)
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
2. Converting Two Lists of the Same Length to a Dictionary
We can convert two lists of the same length to the dictionary using zip().
我们可以使用以下命令将两个相同长度的列表转换为字典 zip() 。
zip()
will return an iterator of tuples. We can convert that zip
object to a dictionary using the dict()
constructor.
zip()
将返回一个元组的迭代器。 我们可以使用以下方式将zip
对象转换为字典 dict()
构造函数。
压缩() (zip())
Make an iterator that aggregates elements from each of the iterables.
创建一个迭代器,以聚合每个可迭代对象中的元素。
例子 Example:
l1=[1,2,3,4]
l2=['a','b','c','d']
d1=zip(l1,l2)
print (d1) # Output:<zip object at 0x01149528>
# Converting zip object to dict using dict() contructor.
print (dict(d1))
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
3.Converting Two Lists of Different Length to a Dictionary
We can convert two lists of different length to the dictionary using itertools.zip_longest()
.
我们可以使用itertools.zip_longest()
将两个不同长度的列表转换成字典。
As per Python documentation
“zip_longest(): Makes an iterator that aggregates elements from each of the iterables. If iterables are of uneven length, missing value is filled with fillvalue. Iteration continues until the longest iterable is exhausted.In zip(),iteration continues until shortest iterable is exhausted.”
“ zip_longest() :创建一个迭代器,以聚合每个可迭代对象中的元素。 如果可迭代项的长度不均匀,则用填充值填充缺失值。 迭代一直持续到最长的可迭代耗尽为止。在zip()中,迭代一直持续到最短的可迭代耗尽为止。”
itertools.zip_longest(*iterables,fillvalue=None)
Using zip()
, iteration continues until the shortest iterable is exhausted.
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip(l1,l2)
print (d1)
# Output:<zip object at 0x01149528>
# Converting zip object to dict using dict() contructor.
print(dict(d1))
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Using zip_longest()
, iteration continues until the longest iterable is exhausted. By default, fillvalue is None.
from itertools import zip_longest
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip_longest(l1,l2)
print (d1) #Output:<itertools.zip_longest object at 0x00993C08>
# Converting zip object to dict using dict() contructor.
print(dict(d1))
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: None, 6: None, 7: None}
fillvalue
is mentioned as x.
from itertools import zip_longest
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip_longest(l1,l2,fillvalue='x')
print (d1) #Output:<itertools.zip_longest object at 0x00993C08>
# Converting zip object to dict using dict() contructor.
print (dict(d1))
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'x', 6: 'x', 7: 'x'}
4. Converting a List of Alternative Key, Value Items to a Dictionary
We can convert a list of alternative keys, values as items to a dictionary using slicing.
Slicing returns a new list containing a sequence of items from the list. We can specify a range of indexes.
s[i:j:k] — slice of s from i to j with step k
We can create two slice lists. The first list contains keys alone and the next list contains values alone.
l1=[1,'a',2,'b',3,'c',4,'d']
Create two slice objects from this list.
从此列表中创建两个切片对象。
The first slice object will contain keys alone
l1[::2]
start
is not mentioned. By default, it will start from the beginning of the list.
stop
is not mentioned. By default, it will stop at the end of the list.
step
is mentioned as 2.
l1[::2]
Returns a list containing elements from beginning to end using step 2 (alternative elements).
[1,2,3,4]
The second slice object will contain values alone
l1=[1,'a',2,'b',3,'c',4,'d']
l1[1::2]
start
is mentioned as 1. It will start slicing from the first index.
stop
is not mentioned. It will stop at the end of the list.
step
is mentioned as 2.
l1[1::2]
Returns a list containing elements from the first index to the end using step 2 (alternative elements).
['a', 'b', 'c', 'd']
Now we can merge the two lists using the zip()
function.
l0=[1,'a',2,'b',3,'c',4,'d']
# Creating list containing keys alone by slicing
l1=l0[::2]
# Creating list containing values alone by slicing
l2=l0[1::2]
# merging two lists uisng zip()
z=zip(l1,l2)
# Converting zip object to dict using dict() constructor.
print(dict(z))
# Output: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
5. Converting a List of Dictionaries to a Single Dictionary
A list of dictionaries can be converted into a single dictionary by the following ways:
dict.update()
- dictionary comprehension
Collections.ChainMap
dict.update()
We can convert a list of dictionaries to a single dictionary using dict.update()
.
- Create an empty dictionary.
- Iterate through the list of dictionaries using a for loop.
- Now update each item (key-value pair) to the empty dictionary using
dict.update()
.
l1=[{1:'a',2:'b'},{3:'c',4:'d'}]
d1={}
for i in l1:
d1.update(i)
print(d1)
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Dictionary comprehension 字典推导式
A dictionary comprehension consists of brackets{}
containing two expressions separated with a colon followed by a for
clause, then zero or more for
or if
clauses.
字典推导式由括号{}
组成,该括号包含两个用冒号分隔的表达式,后跟一个for
子句,然后是零个或多个for
或if
子句。
l1=[{1:'a',2:'b'},{3:'c',4:'d'}]
d1={k:v for e in l1 for (k,v) in e.items()}
for e in l1
— Return each item in the list {1:’a’,2:’b’}.for (k,v) in e.items()
— Return the key, value pair in that item. (1,’a’) (2,’b’)k:v
— is updated in the dictionary d1
l1=[{1:'a',2:'b'},{3:'c',4:'d'}]
d1={k:v for e in l1 for (k,v) in e.items()}
print (d1)
# Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Collections.ChainMap
By using collections.ChainMap()
, we can convert a list of dictionaries to a single dictionary.
As per the Python documentation
“ChainMap
: A ChainMap groups multiple dictionary or other mappings together to create a single, updateable view.”
The return type will be ChainMap
object. We can convert to a dictionary using the dict()
constructor.
l1=[{1:'a',2:'b'},{3:'c',4:'d'}]
from collections import ChainMap
d3=ChainMap(*l1)
print (d3)#Output:ChainMap({1: 'a', 2: 'b'}, {3: 'c', 4: 'd'})
#Converting ChainMap object to dict using dict() constructor.
print (dict(d3))
# Output:{3: 'c', 4: 'd', 1: 'a', 2: 'b'}
6. Converting a List to a Dictionary Using Enumerate()
By using enumerate()
, we can convert a list into a dictionary with index as key and list item as the value.
enumerate()
will return an enumerate object.
We can convert to dict using the dict()
constructor.
As per the Python documentation:
“enumerate(iterable, start=0)
: Returns an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__()
method of the iterator returned by enumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.”
l1=['a','b','c','d']
d1=dict(enumerate(l1))
print (d1)#Output:{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
7. Converting List Into a Dictionary Using Dictionary Comprehension
By using dictionary comprehension, we can convert a list of keys to a dictionary having the same value.
d1={k:"a" for k in l1}
It will iterate through the list and change its item as a key (k
), and value will be a
for all keys.
l1=[1,2,3,4]
d1={k:"a" for k in l1}
print (d1)
# Output:{1: 'a', 2: 'a', 3: 'a', 4: 'a'}
8. Converting a List to a Dictionary Using dict.fromkeys()
dict.fromkeys()
will accept a list of keys, which is converted to dictionary keys, and a value, which is to be assigned.
The same value will be assigned to all keys.
l1=['red','blue','orange']
d1=dict.fromkeys(l1,"colors")
print (d1)
# Output:{'red': 'colors', 'blue': 'colors', 'orange': 'colors'}
9. Converting a Nested List to a Dictionary Using Dictionary Comprehension
We can convert a nested list to a dictionary by using dictionary comprehension.
我们可以使用字典推导式将一个嵌套列表转换为字典
l1 = [[1,2],[3,4],[5,[6,7]]]
d1={x[0]:x[1] for x in l1}
It will iterate through the list.
It will take the item at index 0 as key and index 1 as value.
l1 = [[1,2],[3,4],[5,[6,7]]]
d1={x[0]:x[1] for x in l1}
print(d1)#Output:{1: 2, 3: 4, 5: [6, 7]}
10. Converting a List to a Dictionary Using Counter()
“Counter()
: Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.” — Python documentation
collections.Counter(iterable-or-mapping)
from collections import Counter
c1=Counter(['c','b','a','b','c','a','b'])
# key are elements and corresponding values are their frequencies
print (c1) # Output:Counter({'b': 3, 'c': 2, 'a': 2})
print (dict(c1)) # Output:{'c': 2, 'b': 3, 'a': 2}