- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
dict
支持多个初始化/更新参数:
d = dict([('a',1), ('b',2)]) # list of (key,value)
d = dict({'a':1, 'b':2}) # copy of dict
d = dict(a=1, b=2) #keywords
如何编写处理同一组案例的函数的签名和参数?
我正在编写一个类,我想支持相同的参数集,但只存储 (key,value)
对列表,以便允许多个项目具有相同的键。我希望能够以与 dict
相同的方式添加到字典中的对列表,或者对或关键字列表中。
更新的 C 实现对我来说不是很有帮助,因为我正在 python 中实现它。
最佳答案
这是一个与 dict 行为相同的函数(除了支持多个键的要求之外):
def func(*args, **kwargs):
result = []
if len(args) > 1:
raise TypeError('expected at most 1 argument, got 2')
elif args:
if all(hasattr(args[0], a) for a in ('keys', '__getitem__')):
result.extend(dict(args[0]).items())
else:
for k, v in args[0]:
hash(k)
result.append((k, v))
result.extend(kwargs.items())
return result
一些注意事项:
dict
has lower requirements than that .def func(x=None,/, **kwargs)
。但是,这需要 Python >= 3.8,因此首选向后兼容的解决方案。dict
相同的异常,但消息并不总是完全相同。下面是一些简单的测试,将函数的行为与 dict
构造函数进行比较(尽管它并不试图涵盖所有可能性):
def test(fn):
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'d': 4, 'e': 5, 'f': 6}
class Maplike():
def __getitem__(self, k):
return d1[k]
def keys(self):
return d1.keys()
print('test %s\n=========\n' % fn.__name__)
print('dict:', fn(d1))
print('maplike:', fn(Maplike()))
print('seq:', fn(tuple(d1.items())))
print('it:', fn(iter(d1.items())))
print('gen:', fn(i for i in d1.items()))
print('set:', fn(set(d2.items())))
print('str:', fn(['fu', 'ba', 'r!']))
print('kwargs:', fn(**d1))
print('arg+kwargs:', fn(d1, **d2))
print('dup-keys:', fn(d1, **d1))
print('empty:', fn())
print()
try:
fn(d1, d2)
print('ERROR')
except Exception as e:
print('len-args: %s' % e)
try:
fn([(1, 2, 3)])
print('ERROR')
except Exception as e:
print('pairs: %s' % e)
try:
fn([([], 3)])
print('ERROR')
except Exception as e:
print('hashable: %s' % e)
print()
test(func)
test(dict)
输出:
test func
=========
dict: [('a', 1), ('b', 2), ('c', 3)]
maplike: [('a', 1), ('b', 2), ('c', 3)]
seq: [('a', 1), ('b', 2), ('c', 3)]
it: [('a', 1), ('b', 2), ('c', 3)]
gen: [('a', 1), ('b', 2), ('c', 3)]
set: [('d', 4), ('e', 5), ('f', 6)]
str: [('f', 'u'), ('b', 'a'), ('r', '!')]
kwargs: [('a', 1), ('b', 2), ('c', 3)]
arg+kwargs: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6)]
dup-keys: [('a', 1), ('b', 2), ('c', 3), ('a', 1), ('b', 2), ('c', 3)]
empty: []
len-args: expected at most 1 argument, got 2
pairs: too many values to unpack (expected 2)
hashable: unhashable type: 'list'
test dict
=========
dict: {'a': 1, 'b': 2, 'c': 3}
maplike: {'a': 1, 'b': 2, 'c': 3}
seq: {'a': 1, 'b': 2, 'c': 3}
it: {'a': 1, 'b': 2, 'c': 3}
gen: {'a': 1, 'b': 2, 'c': 3}
set: {'d': 4, 'e': 5, 'f': 6}
str: {'f': 'u', 'b': 'a', 'r': '!'}
kwargs: {'a': 1, 'b': 2, 'c': 3}
arg+kwargs: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
dup-keys: {'a': 1, 'b': 2, 'c': 3}
empty: {}
len-args: dict expected at most 1 argument, got 2
pairs: dictionary update sequence element #0 has length 3; 2 is required
hashable: unhashable type: 'list'
关于python - 如何定义和实现一个行为类似于 dict 构造函数/更新的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60009434/
我有以下数据: foo red test foo red test foo red test2 foo blue test bar red test bar blue test bar red tes
这些字典很长,我需要循环遍历多个键值。举一个简短的例子。从长远来看,我需要将所有数字除以适当的计数以获得平均值。 counts = {'A':10, 'B':14} totals = {'A':{'a
我想构建一个字典,其中一个值是从另一个值构建的。 我想写 d = { 'a':1, 'b':self['a']+1 } 但它没有按预期工作: >>> {'a':1, 'b':self[
这个问题在这里已经有了答案: TypeError: unhashable type: 'dict' (4 个回答) 关闭5年前。 我有这段代码: for element in json[referen
d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort by k'} } 想在 python 中按 k 降序对这个字典进行排序。 有点棘手,
使用 this answer ,我创建了 defaultdict 的 defaultdict。现在,我想把那个嵌套很深的 dict 对象变回一个普通的 python dict。 from collec
我有一个如下所示的数据框: NAME ID 155 ARBITRARY_A 697381 208 ARBITRARY_B 691820 2
在添加类型提示 python 函数中哪个是首选? from typing import List, Dict def example_1() -> List[Dict]: pass def e
有这个字典 -> 字典 -> 列表结构 想要比较这种类型的 2 个结构。 one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp",
我有一个复杂的对象。 目前它是字典列表的字典。但将来可能会发生变化,同时仍然只使用列表和字典。 我想查找所有类型为“datetime”的列表元素或字典值并将它们更改为字符串。 递归搜索似乎有效,但无法
我不知道如何在 html 中显示“净利润”的结果,这是 net_profit/sales 的结果。我不想把这个除法公式直接放在html中,因为除此之外还有很多其他复杂的计算。 那么如何把这个除法结果同
我找不到与此用例类似的问题。 我有一个包含列表的字典,我想从每个列表中提取一个特定的索引,并将其分配到一个具有相同键的新字典中。 dict1 = { 'key1': ['a', 'b', 'c'],
这听起来可能很愚蠢。当我在 python 中重写 dict 时: class idict(dict): def __init__ (self, *args, **kwargs):
我有一个像这样的 dict: { ('America', 25, 'm', 'IT'): 10000, ('America', 22, 'm', 'IT'): 8999, ('
我仍在努力学习 Python 中的字典。是否可以使用正则表达式或 startswith 函数在字典中引用键? 我有以下格式的字典,我正在尝试对“AreaOfInterest1”、“AreaOfInte
这个问题在这里已经有了答案: How to restore a builtin that I overwrote by accident? (3 个答案) 关闭 5 年前。 我不小心为关键字 dic
我只是想知道是否有一种简单的方法可以做到这一点。我有一个从文件解析的特定结构,输出是一个字典列表的一个列表。目前,我只有一些看起来像这样的代码: for i in xrange(len(data)):
我想在字典中匹配字典的数据。这: print(a["myval"]["val1"]) 努力获得所需的输出。但是我想“通配” myval 条目。同时输出 myval2 的结果 print(a['*'][
我想知道这是否是用两个字典更新状态的正确解决方案 var PopulationCityView = React.createClass({ getInitialState: function(
我正在将 CSV 转换为 dict,所有值均已正确加载,但有一个问题。 CSV: Testing testing\nwe are into testing mode My\nServer Thi
我是一名优秀的程序员,十分优秀!