SoFunction
Updated on 2025-03-02

Python list generation and dictionary generation examples

List generation formula

Format

[ x  for  x in Iterable object]
[ x  for  x in Iterable object if condition]

1. Put the element x to be generated in front. When executing, execute the subsequent for loop first.

2. Follow the for loop, there can be multiple for loops, or you can add an if condition after the for loop.

3. The for loop can be followed by an iterator in any way (tuple/list/generator...) as long as there is at least one value in the element of the iterable object.

Example 1: The easiest

In [1]: [x for x in 'abcd']
Out[1]: ['a', 'b', 'c', 'd']

Example 2: Add if judgment

In [1]: res = [10,11,12,13]
In [2]: [x for x in res if x > 10]
Out[2]: [11, 12, 13]

Native implementation:
In [1]: arr = []
In [2]: for x in res:
  ....:     if x > 10:
  ....:         (x)
  ....:         
In [3]: arr
Out[3]: [11, 12, 13]

Example 3: Iterative dictionary generates a list

print [v for k,v in {'a':'one','b':'two'}.items()]
Output:['one', 'two']

print [(k,v) for k,v in {'a':'one','b':'two'}.items()]
Output:[('a', 'one'), ('b', 'two')]

print [k+'='+v for k,v in {'name':'lyz','age':'26','job':'IT'}.items()]
Output:['job=IT', 'age=26', 'name=lyz']

Dictionary Generation

Format

1. In Python 2.6 or earlier, the dictionary generator can accept iterative key/value pairs.

d = dict((key, value) for (key, value) in iterable)

illustrate:

The first k and v () must be written, and the second () cannot be written.

Version 2.6 uses the dict() function. The parameters of the function are a nested sequence and the elements of the sequence are tuples.

2. From Python 2.7 or 3, you can directly deduce the syntax using dictionary.

d = {key: value for (key, value) in iterable} # k,v's () can be written without writing

3. Python 2.7 or above is compatible with two writing methods, and Python 2.6 can only use the first one.

4. Iterators (tuples, lists, generators...) can be used in any way, as long as there are two values ​​in the elements of the iterable object.

How to write python2.7

dict1 = {'one':1,'two':2,'three':3}
dict2 = {v:k for k,v in ()}
print dict2
Output:
{1: 'one', 2: 'two', 3: 'three'}

Python 2.6 writing method

dict1 = {'one':1,'two':2,'three':3}
dict3 = dict((v,k) for k,v in ())
print dict3
Output:
{1: 'one', 2: 'two', 3: 'three'}

Example 1: Two generational methods to generate dictionaries

In [1]: arr=['wd','18','nan']
In [2]: dict((k,v) for k,v in enumerate(arr))
Out[2]: {0: 'wd', 1: '18', 2: 'nan'}
In [3]: {k:v for k,v in enumerate(arr)}
Out[3]: {0: 'wd', 1: '18', 2: 'nan'}

Example 2: Online Example

arr = [{'id':1,'name':'lyz','age':26},{'id':2,'name':'pc','age':30}]
print {str(x['id']):x['name'] for x in arr}
Execution results:
{'1': 'lyz', '2': 'pc'}

Other ways to generate dictionary

1. dict() function

Nested tuples and nested categories can be converted into dictionaries directly through the dict command (there can only be 2 elements inside the nest)

>>> a = [(1, 'ab'), (2, 'bc')]
>>> dict(a)
{1: 'ab', 2: 'bc'}

>>> result = ((1, 'ab'), (2, 'bc'))
>>> dict(result)
{1: 'ab', 2: 'bc'}

2. zip() function

Merge multiple tuples or lists. The merge rule is that the number of elements in each tuple is the same.

In [1]: zip(('name','age','sex'),('wd','18','nan'))
Out[1]: [('name', 'wd'), ('age', '18'), ('sex', 'nan')]

In [2]: zip(['name','age','sex'],['wd','18','nan'])
Out[2]: [('name', 'wd'), ('age', '18'), ('sex', 'nan')]

In [3]: dict(zip(('name','age','sex'),('wd','18','nan')))  # Most commonly used in production environmentsOut[3]: {'age': '18', 'name': 'wd', 'sex': 'nan'}

In [4]: zip(['name','age','sex'],['wd','18','nan'],['11',22])  # The number of list elements is inconsistent, the minimum list should beOut[4]: [('name', 'wd', '11'), ('age', '18', 22)]

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.