以下代码简单而清晰,在编译时会产生错误:
import string
import collections
#create dictionary with alphabets as keys, and empty values
list = ['aema', 'airplane', 'amend']
gen_dict = dict.fromkeys(string.ascii_lowercase, '')
gen_dict = collections.defaultdict(list)
for x in list:
gen_dict['a'].append(x)
Run Code Online (Sandbox Code Playgroud)
并产生的错误是:
Traceback (most recent call last):
File "indexdict.py", line 14, in <module>
gen_dict = collections.defaultdict(list)
TypeError: first argument must be callable
Run Code Online (Sandbox Code Playgroud)
任何的想法?提前致谢
Lua中是否有类似于collections.defaultdict
Python中的功能,它可以自动处理不存在的关联数组键的默认值?
我希望下面的代码设置nil
为v
而不是错误.所以基本上默认情况下a[2]
(不存在的键)是一种方法table
:
a = {}
v = a[2][3]
>>> PANIC: unprotected error in call to Lua API (main.lua:603: attempt to index field '?' (a nil value))
Run Code Online (Sandbox Code Playgroud)
在Python中,它可以这样做:
>>> import collections
>>> a = collections.defaultdict(dict)
>>> print a[2]
{}
Run Code Online (Sandbox Code Playgroud) 因此,我需要通过第element
一个第二个嵌套列表(使用类似01, 02, 03
等元素)对这种列表中的一些随机数据进行排序:
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]
Run Code Online (Sandbox Code Playgroud)
这个随机数据稍后在defaultdict中与其他一些数据一起使用,以便将它们组合在一起并通过键打印出来(键是数字00553, 00551
).
我尝试在将它放到defaultdict之前对它进行排序,但我得到的所有内容都是嵌套列表本身的值.
任何人都可以帮助我,我是新手.
我有一个defaultdict,其中键是一个4元组(gene_region,种类,本体,长度).
循环使用很简单:
for gene_region, species, ontology, length in result_dict:
Run Code Online (Sandbox Code Playgroud)
但是,我想以嵌套方式迭代它,如下所示:
for gene_region
for species
for ontology
...
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?没有其他方法可以先收集价值吗?或使用以下dum-dum方式:
for gene_region, _, _, _ in result_dict:
for _, species, _, _ in result_dict:
...
Run Code Online (Sandbox Code Playgroud) 说我同意:
import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')
Run Code Online (Sandbox Code Playgroud)
然后我选择一个随机元素:
random.choice(d)
Run Code Online (Sandbox Code Playgroud)
现在让我们打印d
:
defaultdict(list, {0: [], 'foo': ['bar']})
Run Code Online (Sandbox Code Playgroud)
为什么要random.choice
添加0
为关键?
我有一份命令字典。我想将所有这些组合在一起,然后按每个中的fruit属性对其进行排序。我一直在通过下面的代码使用defaultdict对它们进行组合和排序。
super_dict_apple = defaultdict(list)
super_dict_orange = defaultdict(list)
super_dict_no_fruit = defaultdict(list)
for d in dict:
if 'fruit' not in d:
for k, v in d.iteritems():
super_dict_no_fruit[k].append(v)
elif d['fruit'] == 'Apple':
for k, v in d.iteritems():
super_dict_apple[k].append(v)
elif d['fruit'] == 'orange':
for k, v in d.iteritems():
super_dict_orange[k].append(v)
Run Code Online (Sandbox Code Playgroud)
这样我得到了一个键和所有相关的值,但是我失去了原始顺序。因此,我尝试使用orderDict来执行此操作,但是我无法使其正常工作,以下是我尝试过的操作。
from collections import OrderedDict
order_dict_no_fruit = OrderedDict()
order_dict_apple = OrderedDict()
order_dict_orange = OrderedDict()
for d in dict:
if 'fruit' not in d:
for k, v in d.iteritems():
order_dict_no_fruit[k].append(v)
elif d['fruit'] == 'Apple':
for k, …
Run Code Online (Sandbox Code Playgroud) python ordereddictionary data-structures defaultdict dictionary-missing
不幸的是,对我来说,我需要使脚本向后兼容w/Python 2.4,并且defaultdict
在2.4版本中不存在.
什么可以替代呢?
给定键的数据结构是以下列表:
[{'red': (12, 1, 12), 'white': (30, 2, 60), 'blue': (8, 1, 4), 'orange': (9, 4, 8), 'black': (10, 12, 4)}]
Run Code Online (Sandbox Code Playgroud)
编辑:添加使用信息.首先,我用以下内容构建默认dict:
defDict[key1].append(... ...)
Run Code Online (Sandbox Code Playgroud)
然后它传递给密钥的几种方法:val(列表)查找和密钥删除.
特别是删除:
if len(defDict[key1][0]) == 0:
del defDict[key1]
Run Code Online (Sandbox Code Playgroud)
编辑:NoneType上的错误
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
print defDict[key]
print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
if len(defDict[key][0]) == 0:
#del defDict[key]
Run Code Online (Sandbox Code Playgroud)
错误:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
None
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
if len(defDict[key][0]) == 0:
TypeError: 'NoneType' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)
我认为错误来自key
:
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
print defDict[key]
print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
Run Code Online (Sandbox Code Playgroud)
输出:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
None
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
Run Code Online (Sandbox Code Playgroud) 我正在尝试在Python中创建嵌套字典的数据结构.我将2个类似sql-table的关系csv文件读入数据帧,然后逐行将它们转换为字典.在这些词典中,我存储了我从另一个csv创建的词典.
只要我将字典直接存储在dict键中,我的代码就可以正常工作.
但我真正想要的是data[id]['ticket']
包含一个字典列表.(1位客户可以拥有多张门票)
import json
import pandas as pd
import collections
# Import csv into dataframe (maybe not necessesary)
df1 = pd.read_csv('customer.csv', sep=';', header=0, dtype=object, na_filter=False)
df2 = pd.read_csv('tickets.csv', sep=';', header=0, dtype=object, na_filter=False)
df1['tickets'] = '' #create new empty column in dataframe 1
data = collections.defaultdict(dict)
# Convert initial dataframe to dictionary of dictionarys
for index, row in df1.iterrows():
row_dict = row.to_dict()
data[row_dict['id']] = row_dict
data[row_dict['id']]['tickets'] = []
# Convert each row of dataframe 2 to into dictionary …
Run Code Online (Sandbox Code Playgroud) 在defaultdict
对象中查询缺少的键时,该键会自动添加到字典中:
from collections import defaultdict
d = defaultdict(int)
res = d[5]
print(d)
# defaultdict(<class 'int'>, {5: 0})
# we want this dictionary to remain empty
Run Code Online (Sandbox Code Playgroud)
但是,我们通常只想在显式或隐式分配密钥时添加密钥:
d[8] = 1 # we want this key added
d[3] += 1 # we want this key added
Run Code Online (Sandbox Code Playgroud)
一个用例是简单计数,以避免更高的开销collections.Counter
,但是这个特征通常也是可取的.
反例 [原谅双关语]
这是我想要的功能:
from collections import Counter
c = Counter()
res = c[5] # 0
print(c) # Counter()
c[8] = 1 # key added successfully
c[3] += 1 # …
Run Code Online (Sandbox Code Playgroud) 我得到一些奇怪的行为colletions.defaultdict
:
import collections
c1 = collections.defaultdict(str)
c1['new'] # Works!
c2 = collections.defaultdict(default_factory=str)
c2['new'] # Raises KeyError...
Run Code Online (Sandbox Code Playgroud)
为什么会引发c2
KeyError?
有时我喜欢命名参数,因为我认为它增加了可读性.
首先我想也许python不允许我通过命名传递参数并将我的default_factory
参数放到kwargs,所以我检查:
def func(first, **kwargs):
print(first)
print(kwargs)
func(first='one', second='two')
Run Code Online (Sandbox Code Playgroud)
这输出:
one
{'second': 'two'}
Run Code Online (Sandbox Code Playgroud)
所以事实并非如此.
defaultdict ×10
python ×10
dictionary ×4
collections ×1
json ×1
list ×1
lua ×1
oop ×1
pandas ×1
python-2.4 ×1
python-3.x ×1
tuples ×1