创建具有理解力的字典

发布于 2024-08-11 15:26:41 字数 110 浏览 8 评论 0原文

我可以使用列表理解语法来创建字典吗?

例如,通过迭代键和值对:

d = {... for k, v in zip(keys, values)}

Can I use list comprehension syntax to create a dictionary?

For example, by iterating over pairs of keys and values:

d = {... for k, v in zip(keys, values)}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

就像说晚安 2024-08-18 15:26:41

使用 字典理解(Python 2.7 及更高版本):

{key: value for key, value in zip(keys, values)}

或者,使用 < a href="https://docs.python.org/3/library/stdtypes.html#typesmapping" rel="noreferrer">dict 构造函数:

pairs = [('a', 1), ('b', 2)]
dict(pairs)                          # → {'a': 1, 'b': 2}
dict((k, v + 10) for k, v in pairs)  # → {'a': 11, 'b': 12}

给定单独的键列表和值,使用 dict 构造函数和 zip< /代码>

keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))              # → {'a': 1, 'b': 2}

Use a dict comprehension (Python 2.7 and later):

{key: value for key, value in zip(keys, values)}

Alternatively, use the dict constructor:

pairs = [('a', 1), ('b', 2)]
dict(pairs)                          # → {'a': 1, 'b': 2}
dict((k, v + 10) for k, v in pairs)  # → {'a': 11, 'b': 12}

Given separate lists of keys and values, use the dict constructor with zip:

keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))              # → {'a': 1, 'b': 2}
羞稚 2024-08-18 15:26:41

在 Python 3 和 Python 2.7+ 中,字典推导式如下所示:

d = {k:v for k, v in iterable}

对于 Python 2.6 或更早版本,请参阅 fortran 的答案

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran's answer.

念﹏祤嫣 2024-08-18 15:26:41

事实上,如果 iterable 已经理解某种映射,你甚至不需要迭代它, dict 构造函数会慷慨地为你做这件事:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}
梦亿 2024-08-18 15:26:41

在 Python 中创建具有列表推导式的字典

我喜欢 Python 列表理解语法。

它也可以用来创建字典吗?例如,通过迭代
在键和值对上:

mydict = {(k,v) for (k,v) in blah blah blah}

您正在寻找短语“字典理解” - 它实际上是:

mydict = {k: v for k, v in iterable}

假设 blah blah blah 是二元组的可迭代 - 你非常接近。让我们创建一些像这样的“废话”:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

字典理解语法:

现在这里的语法是映射部分。是什么使它成为 dict 理解而不是 set 理解(这就是您的伪代码的近似值)是冒号,: 如下所示:

mydict = {k: v for k, v in blahs}

我们看到它有效,并且应该保留 Python 3.7 的插入顺序:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}

在 Python 2 和 3.6 之前,不能保证顺序:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

添加过滤器:

所有推导式都具有映射组件和过滤组件,您可以使用它们提供任意表达。

所以你可以在末尾添加一个过滤部分:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

这里我们只是测试最后一个字符是否能被2整除,以在映射键和值之前过滤掉数据。

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating
over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}

You're looking for the phrase "dict comprehension" - it's actually:

mydict = {k: v for k, v in iterable}

Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Dict comprehension syntax:

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudo-code approximates) is the colon, : like below:

mydict = {k: v for k, v in blahs}

And we see that it worked, and should retain insertion order as-of Python 3.7:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}

In Python 2 and up to 3.6, order was not guaranteed:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Adding a Filter:

All comprehensions feature a mapping component and a filtering component that you can provide with arbitrary expressions.

So you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we are just testing for if the last character is divisible by 2 to filter out data before mapping the keys and values.

活泼老夫 2024-08-18 15:26:41

在 Python 2.7 中,它就像:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

压缩它们

In Python 2.7, it goes like:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

Zip them!

染火枫林 2024-08-18 15:26:41

Python 版本 >= 2.7,执行以下操作:

d = {i: True for i in [1,2,3]}

Python 版本 2.7(RIP,2010年7月3日 - 2019年12月31日),执行以下操作:

d = dict((i,True) for i in [1,2,3])

Python version >= 2.7, do the below:

d = {i: True for i in [1,2,3]}

Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:

d = dict((i,True) for i in [1,2,3])
最初的梦 2024-08-18 15:26:41

要添加@fortran的答案,如果您想迭代键列表key_list以及值列表value_list

d = dict((key, value) for (key, value) in zip(key_list, value_list))

d = {key: value for (key, value) in zip(key_list, value_list)}

To add onto @fortran's answer, if you want to iterate over a list of keys key_list as well as a list of values value_list:

d = dict((key, value) for (key, value) in zip(key_list, value_list))

or

d = {key: value for (key, value) in zip(key_list, value_list)}
谁把谁当真 2024-08-18 15:26:41

再举一个例子。想象一下您有以下列表:

nums = [4,2,2,1,3]

并且您想将其转换为字典,其中键是索引,值是列表中的元素。您可以使用以下代码行来执行此操作:

{index:nums[index] for index in range(0,len(nums))}

Just to throw in another example. Imagine you have the following list:

nums = [4,2,2,1,3]

and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:

{index:nums[index] for index in range(0,len(nums))}
極樂鬼 2024-08-18 15:26:41

此代码将使用列表理解为具有不同值的多个列表创建字典,这些列表可用于 pd.DataFrame()

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

#Convert dict to dataframe
df=pd.DataFrame(data)
display(df)

enumerate 将传递 nvals 将每个 key 与其列表进行匹配

This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

#Convert dict to dataframe
df=pd.DataFrame(data)
display(df)

enumerate will pass n to vals to match each key with its list

痴意少年 2024-08-18 15:26:41

这是使用字典理解创建字典的另一个示例:

我在这里要做的是创建一个字母字典,其中每对;是英文字母及其在英文字母表中的对应位置

>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in 
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>> 

注意这里使用 enumerate 来获取字母表及其在列表中的索引,并交换字母表和索引以生成字典的键值对

希望它给出了一个好主意字典比较给你并鼓励你更频繁地使用它来使你的代码紧凑

Here is another example of dictionary creation using dict comprehension:

What i am tring to do here is to create a alphabet dictionary where each pair; is the english letter and its corresponding position in english alphabet

>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in 
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>> 

Notice the use of enumerate here to get a list of alphabets and their indexes in the list and swapping the alphabets and indices to generate the key value pair for dictionary

Hope it gives a good idea of dictionary comp to you and encourages you to use it more often to make your code compact

栖竹 2024-08-18 15:26:41

如果您想从列表中查找dict,请添加到@Ekhtiar答案,你可以使用这个:

names = ['a', 'b', 'd', 'f', 'c']
names_to_id = {v:k for k, v in enumerate(names)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'f': 4}

或者在极少数情况下,你想过滤重复项,首先使用set(最好在数字列表中):

names = ['a', 'b', 'd', 'f', 'd', 'c']
sorted_list = list(set(names))
sorted_list.sort()
names_to_id = {v:k for k, v in enumerate(sorted_list)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'f': 4}

names = [1,2,5,5,6,2,1]
names_to_id = {v:k for k, v in enumerate(set(names))}
# {1: 0, 2: 1, 5: 2, 6: 3}

Adding to @Ekhtiar answer, if you want to make look up dict from list, you can use this:

names = ['a', 'b', 'd', 'f', 'c']
names_to_id = {v:k for k, v in enumerate(names)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'f': 4}

Or in rare case that you want to filter duplicate, use set first (best in list of number):

names = ['a', 'b', 'd', 'f', 'd', 'c']
sorted_list = list(set(names))
sorted_list.sort()
names_to_id = {v:k for k, v in enumerate(sorted_list)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'f': 4}

names = [1,2,5,5,6,2,1]
names_to_id = {v:k for k, v in enumerate(set(names))}
# {1: 0, 2: 1, 5: 2, 6: 3}
我的痛♀有谁懂 2024-08-18 15:26:41

试试这个,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

假设我们有两个列表 countrycapital

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

然后从两个列表创建字典:

print get_dic_from_two_lists(country, capital)

输出如下,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

Try this,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

Assume we have two lists country and capital

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

Then create dictionary from the two lists:

print get_dic_from_two_lists(country, capital)

The output is like this,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}
伊面 2024-08-18 15:26:41
>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}

Python 支持字典推导式,它允许您使用类似的简洁语法在运行时表达字典的创建。

字典理解采用 {key: value for (key, value) in iterable} 的形式。此语法是在 Python 3 中引入的,并向后移植到 Python 2.7,因此无论您安装的是哪个版本的 Python,您都应该能够使用它。

一个典型的例子是采用两个列表并创建一个字典,其中第一个列表中每个位置的项目成为键,第二个列表中相应位置的项目成为值。

此推导式中使用的 zip 函数返回一个元组迭代器,其中元组中的每个元素均取自每个输入可迭代对象中的相同位置。在上面的示例中,返回的迭代器包含元组 (“a”, 1)、(“b”, 2) 等。

输出:

{'i': 512, 'e': 64, 'o': 2744, 'h': 343, 'l': 1331, 's': 5832, 'b': 1, 'w': 10648, 'c': 8, 'x': 12167, 'y': 13824, 't': 6859, 'p': 3375, 'd': 27, 'j': 729, 'a': 0, 'z': 15625, 'f': 125, 'q': 4096, 'u': 8000, 'n': 2197, 'm': 1728, 'r': 4913, 'k': 1000, 'g': 216, 'v': 9261}
>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}

Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax.

A dictionary comprehension takes the form {key: value for (key, value) in iterable}. This syntax was introduced in Python 3 and backported as far as Python 2.7, so you should be able to use it regardless of which version of Python you have installed.

A canonical example is taking two lists and creating a dictionary where the item at each position in the first list becomes a key and the item at the corresponding position in the second list becomes the value.

The zip function used inside this comprehension returns an iterator of tuples, where each element in the tuple is taken from the same position in each of the input iterables. In the example above, the returned iterator contains the tuples (“a”, 1), (“b”, 2), etc.

Output:

{'i': 512, 'e': 64, 'o': 2744, 'h': 343, 'l': 1331, 's': 5832, 'b': 1, 'w': 10648, 'c': 8, 'x': 12167, 'y': 13824, 't': 6859, 'p': 3375, 'd': 27, 'j': 729, 'a': 0, 'z': 15625, 'f': 125, 'q': 4096, 'u': 8000, 'n': 2197, 'm': 1728, 'r': 4913, 'k': 1000, 'g': 216, 'v': 9261}
迷爱 2024-08-18 15:26:41

是的,这是可能的。在python中,推导式可以用在List、Set、Dictionary等中。
你可以这样写

mydict = {k:v for (k,v) in blah}

另一个使用条件语句和循环进行字典理解的详细示例:

parents = [father, mother]
            
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}

Yes, it's possible. In python, Comprehension can be used in List, Set, Dictionary, etc.
You can write it this way

mydict = {k:v for (k,v) in blah}

Another detailed example of Dictionary Comprehension with the Conditional Statement and Loop:

parents = [father, mother]
            
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}
┈┾☆殇 2024-08-18 15:26:41

您可以为每一对创建一个新的字典,并将其与前一个字典合并:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

显然,这种方法需要来自 functoolsreduce

You can create a new dict for each pair and merge it with the previous dict:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

Obviously this approaches requires reduce from functools.

机场等船 2024-08-18 15:26:41

假设 blah blah blah 是一个二元组列表:

让我们看看两种方法:

# method 1
>>> lst = [('a', 2), ('b', 4), ('c', 6)]
>>> dict(lst)
{'a': 2, 'b': 4, 'c': 6}
# method 2
>>> lst = [('a', 2), ('b', 4), ('c', 6)]
>>> d = {k:v for k, v in lst}
>>> d
{'a': 2, 'b': 4, 'c': 6}

Assuming blah blah blah is a two-tuples list:

Let's see two methods:

# method 1
>>> lst = [('a', 2), ('b', 4), ('c', 6)]
>>> dict(lst)
{'a': 2, 'b': 4, 'c': 6}
# method 2
>>> lst = [('a', 2), ('b', 4), ('c', 6)]
>>> d = {k:v for k, v in lst}
>>> d
{'a': 2, 'b': 4, 'c': 6}
桃扇骨 2024-08-18 15:26:41

此方法使用 for 循环对给定日期进行迭代。

Syntax: {key: value for (key, value) in data}

例如:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}

this approach uses iteration over the given date using a for loop.

Syntax: {key: value for (key, value) in data}

Eg:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文