标签: dictionary-comprehension

字典理解中的海象运算符

我想避免在字典理解中对平均值进行双重评估,并且我尝试使用海象运算符:

>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
Run Code Online (Sandbox Code Playgroud)

但这给了我以下错误:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  File "<pyshell#2>", line 1, in <dictcomp>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  NameError: name …
Run Code Online (Sandbox Code Playgroud)

python dictionary-comprehension python-3.9 walrus-operator

14
推荐指数
1
解决办法
3653
查看次数

Python - 在dict理解中解组的元组

我正在尝试编写一个函数,将表单的字符串'A=5, b=7'转换为字典{'A': 5, 'b': 7}.以下代码片段是主for循环内部发生的- 它们将字符串的单个部分转换为单个dict元素.

这可以:

s = 'A=5'
name, value = s.split('=')
d = {name: int(value)}
Run Code Online (Sandbox Code Playgroud)

这不是:

s = 'A=5'
d = {name: int(value) for name, value in s.split('=')}
ValueError: need more than 1 value to unpack
Run Code Online (Sandbox Code Playgroud)

为什么我不能在字典理解中解包元组?如果我得到这个工作,那么我可以轻松地将整个功能变成一个紧凑的字典理解.

python dictionary dictionary-comprehension iterable-unpacking

12
推荐指数
3
解决办法
8104
查看次数

Python - 在嵌套字典中查找特定值的父键

我很难处理嵌套字典,并且当嵌套字典中的Value可能存在多次时,返回嵌套的父键,用于特定的值.例如:

example_dict = { 'key1' : 'value1',
                 'key2' : 'value2',
                 'key3' : { 'key3a': 'value3a' },
                 'key4' : { 'key4a': { 'key4aa': 'value4aa',
                                       'key4ab': 'value4ab',
                                       'key4ac': 'value1'},
                            'key4b': 'value4b'}
                }
Run Code Online (Sandbox Code Playgroud)

你会注意到'value1'在上面的字典中出现了两次,我想创建一个函数,它返回一个列表或一系列列表,用于标识不同的父键,在本例中为'key1 '和''key4','key4a',key4ac).

这个类型的问题在本网站的其他地方得到了处理,当Value one只寻找出现一次时,可以通过以下递归函数轻松处理:

def find_key(d,key):
    for k,v in d.items():
        if isinstance(v,dict):
            p = find_key(v,key)
            if p:
                return [k] + p
        elif v == key:
            return [k]

print find_key(example_dict,'value4ac').
Run Code Online (Sandbox Code Playgroud)

如果你在字典上运行上面的代码,我只得到一个父键的答案.任何帮助将不胜感激,谢谢!

python dictionary nested key dictionary-comprehension

12
推荐指数
2
解决办法
7793
查看次数

为什么这个python代码表现出奇怪的范围规则

我正在运行Python 2.7.8(Anaconda Distribution),这段代码失败了.这看起来像Python实现中的一个错误,但我错过了什么?

class C:
    x = {2 : 1}
    y = {w for w in x if x[w]==1}
Run Code Online (Sandbox Code Playgroud)

运行此代码会出现以下错误消息:

NameError:未定义全局名称"x"

错误信息对我来说似乎也是错误的.

请注意,以下两个非常相似的代码片段可以正常工作:

# this works fine:
class C:
    x = {2 : 1}
    y = [w for w in x if x[w]==1]


# this works fine too:
x = {2 : 1}
y = {w for w in x if x[w]==1}
Run Code Online (Sandbox Code Playgroud)

python list-comprehension scoping dictionary-comprehension

12
推荐指数
0
解决办法
145
查看次数

将包含列表项的dict扩展为dict对列表

如果我有一个字典,其中包含一个或多个值中的列表:

data = {
  'a':0,
  'b':1,
  'c':[0, 1, 2],
  'pair':['one','two']
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到一个dict元组列表,pair并且迭代结束c,其他所有元素保持不变?例如

output = [
    ({
        'a':0,
        'b':1,
        'c':0,
        'pair':'one'
    },
    {
        'a':0,
        'b':1,
        'c':0,
        'pair':'two'
    }),
    ({
        'a':0,
        'b':1,
        'c':1,
        'pair':'one'
    },
    ...
]
Run Code Online (Sandbox Code Playgroud)

python dictionary list-comprehension python-2.7 dictionary-comprehension

12
推荐指数
1
解决办法
1314
查看次数

通过理解迭代字典并获得字典

如何通过字典理解迭代字典来处理它.

>>> mime_types={
    '.xbm': 'image/x-xbitmap',
    '.dwg': 'image/vnd.dwg',
    '.fst': 'image/vnd.fst',
    '.tif': 'image/tiff',
    '.gif': 'image/gif',
    '.ras': 'image/x-cmu-raster',
    '.pic': 'image/x-pict',
    '.fh':  'image/x-freehand',
    '.djvu':'image/vnd.djvu',
    '.ppm': 'image/x-portable-pixmap',
    '.fh4': 'image/x-freehand',
    '.cgm': 'image/cgm',
    '.xwd': 'image/x-xwindowdump',
    '.g3':  'image/g3fax',
    '.png': 'image/png',
    '.npx': 'image/vnd.net-fpx',
    '.rlc': 'image/vnd.fujixerox.edmics-rlc',
    '.svgz':'image/svg+xml',
    '.mmr': 'image/vnd.fujixerox.edmics-mmr',
    '.psd': 'image/vnd.adobe.photoshop',
    '.oti': 'application/vnd.oasis.opendocument.image-template',
    '.tiff':'image/tiff',
    '.wbmp':'image/vnd.wap.wbmp'
}

>>> {(key,val) for key, val in mime_types.items() if "image/tiff" == val}
Run Code Online (Sandbox Code Playgroud)

这是返回结果,如下所示:

set([('.tiff', 'image/tiff'), ('.tif', 'image/tiff')])
Run Code Online (Sandbox Code Playgroud)

但我期待着

('.tif', 'image/tiff')
Run Code Online (Sandbox Code Playgroud)

如何修改该结果以获取如下字典:

{'.tif': 'image/tiff'}
Run Code Online (Sandbox Code Playgroud)

python dictionary dictionary-comprehension

11
推荐指数
3
解决办法
2万
查看次数

使用dict理解时的问题.NameError:未定义全局名称

我正在尝试使用key as name和value 创建一个dict 作为相应的User对象.

我从Django shell包装器使用Python shell python manage.py shell:

>>> from django.contrib.auth.models import User
>>> names = ['carl', 'jim', 'jack', 'john', 'mark']
# Now using some dict comprehension
>>> u = {name: User.objects.get(username=name) for name in names}
NameError: global name 'User' is not defined
Run Code Online (Sandbox Code Playgroud)

但是,这对我有用:

u = {}
for name in names:
    u[name] = User.objects.get(username=name)
Run Code Online (Sandbox Code Playgroud)

我得到了所需的输出,即:

{ 
  'carl': <User: carl>,
  'jack': <User: jack>,
  'jim' : <User: jim>,
  'john': <User: john>,
  'mark': <User: mark>
} …
Run Code Online (Sandbox Code Playgroud)

python shell dictionary namespaces dictionary-comprehension

9
推荐指数
1
解决办法
2542
查看次数

如果有重复键,python dict理解总是"最后胜利"

如果我创建一个带有dict理解的python字典,但是有重复的键,我保证最后一个项目最终会出现在最后一个字典中吗?我不清楚https://www.python.org/dev/peps/pep-0274/

new_dict = {k:v for k,v in [(1,100),(2,200),(3,300),(1,111)]}
new_dict[1] #is this guaranteed to be 111, rather than 100?
Run Code Online (Sandbox Code Playgroud)

python dictionary duplicates dictionary-comprehension

9
推荐指数
3
解决办法
2020
查看次数

Python字典理解中的条件表达式

a = {"hello" : "world", "cat":"bat"}

# Trying to achieve this
# Form a new dictionary only with keys with "hello" and their values
b = {"hello" : "world"}

# This didn't work

b = dict( (key, value) if key == "hello" for (key, value) in a.items())
Run Code Online (Sandbox Code Playgroud)

关于如何在字典理解中包含条件表达式以决定是否应将键元组值包含在新字典中的任何建议

python dictionary-comprehension

8
推荐指数
2
解决办法
2万
查看次数

使用有序字典作为有序集

既然Python 3.7使得保留顺序的dicts 正式成为语言规范的一部分而不是实现细节,那么我一直在努力探讨如何最好地使用这个属性.今天,我发现我需要一个订单保留集,并认为字典可以做到这一点.

假设我们有一个hashable元素列表.我们需要一个唯一条目列表,我们希望根据首次出现保留这些条目的顺序.一个简单的字典构造函数应该做的伎俩:

ls = "Beautiful is better than ugly. Explicit..."
uniques = list({s:0 for s in ls})

>>> ['B', 'e', 'a', 'u', 't', 'i', 'f', 'l', ' ', 's', 'b', 'r', 'h', 'n', 'g', 'y', '.', 'E', 'x', 'p', 'c']
Run Code Online (Sandbox Code Playgroud)

这将通过首次出现保留排序并消除所有重复.

我想知道社区对这个用例以及一般的订单保留功能的看法.

  • 有没有理由不使用这种方法?
  • 有没有更好的方法来解决这个问题?
  • 这种方法是Pythonic吗?

通过Python的Zen阅读,我很矛盾.该方法很简单,但依赖于隐式排序.

请让我知道你在想什么.谢谢.

python python-3.x dictionary-comprehension python-3.7

8
推荐指数
2
解决办法
1770
查看次数