Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在词典中填写词典_Python_List_Dictionary - Fatal编程技术网

Python 在词典中填写词典

Python 在词典中填写词典,python,list,dictionary,Python,List,Dictionary,我有两份清单: num = ['10', '10', '10', '88', '77', '77', '10'] typ = ['KB', 'BK', 'KB', 'TP', 'HK', 'KH', 'KB'] 我想制作一本字典,其外观如下: {'10':{'KB':3, 'BK':1}, '88':{'TP':1}, '77':{'HK':1, 'KH':1}} 我将有一个主要的数字字典,对于每个数字,我想计算每个数字中出现的“typ” 我试过这个: di={} for i in num

我有两份清单:

num = ['10', '10', '10', '88', '77', '77', '10']
typ = ['KB', 'BK', 'KB', 'TP', 'HK', 'KH', 'KB']
我想制作一本字典,其外观如下:

{'10':{'KB':3, 'BK':1}, '88':{'TP':1}, '77':{'HK':1, 'KH':1}}
我将有一个主要的数字字典,对于每个数字,我想计算每个数字中出现的“typ”

我试过这个:

di={}

for i in num:
    if i not in di:
        di[i]={}     
        for x in typ:
            di[i][x]+=1
并获取以下错误:

KeyError: 'KB'

为num中的每个数字填写字典的最佳方法是什么?

您从未检查
x
是否在
di[i]
中,因此您不能
+=1
,因为它不存在

di={}

for i in num:
    if i not in di:
        di[i]={}     
        for x in typ:
            if x not in di[i]:
                di[i][x] = 0
            di[i][x]+=1
由于您希望默认值为零,Python可以使用
defaultdict

import collections
di = collections.defaultdict(lambda: collections.defaultdict(int))
for i in num:
    for x in typ:
        di[i][x] += 1
要结合其他一些答案,请使用
zip

import collections
di = collections.defaultdict(lambda: collections.defaultdict(int))
for n, t in zip(num, typ):
    di[n][t] += 1
d ={}

for n,t in zip(num,typ):
    if n not in d:
        d[n] = {t:1}
    else:
        if t not in d[n]:
            d[n][t] = 1
        else:
            d[n][t] += 1
这是我的机会

num = ['10', '10', '10', '88', '77', '77', '10']
typ = ['KB', 'BK', 'KB', 'TP', 'HK', 'KH', 'KB']

result ={}

for x,y in enumerate(num):
    if not y in result.keys():
        result[y] = dict()
    try:
        result[y][typ[x]] += 1
    except KeyError:
        result[y][typ[x]] = 1

print(result)

您可以尝试使用
zip

import collections
di = collections.defaultdict(lambda: collections.defaultdict(int))
for n, t in zip(num, typ):
    di[n][t] += 1
d ={}

for n,t in zip(num,typ):
    if n not in d:
        d[n] = {t:1}
    else:
        if t not in d[n]:
            d[n][t] = 1
        else:
            d[n][t] += 1
输出:

{'10': {'BK': 1, 'KB': 3}, '77': {'HK': 1, 'KH': 1}, '88': {'TP': 1}}
您可以将
zip()
dict.get()
一起使用:


你的问题是你说的
+=1
。第一次这样做时,
di[i][x]
尚未定义
di[i][x]+=1
几乎是
di[i][x]=di[i][x]+1
的快捷方式,但由于您尚未定义
di[i][x]
,因此出现了一个键错误。然而,在我的例子中,我使用了
di[n].get(t,0)
,这意味着
di[n][t]
如果
di[n]
具有键
t
,则使用0。以下是使用and的简短解决方案:

集合中使用

>>> from collections import defaultdict, Counter
>>> d = defaultdict(list)
>>> for item in zip(num, typ):
...     d[item[0]].append(item[1])
... 
>>> {key:Counter(values) for key, values in d.items()}
{'88': Counter({'TP': 1}), '77': Counter({'HK': 1, 'KH': 1}), '10': Counter({'KB': 3, 'BK': 1})}
如果您觉得需要转换为
dict
,则:

>>> {key:dict(Counter(values)) for key, values in d.items()}
{'88': {'TP': 1}, '77': {'HK': 1, 'KH': 1}, '10': {'KB': 3, 'BK': 1}}
您也可以使用
setdefault
方法代替
计数器

>>> d = {}
>>> for item in zip(num, typ):
...     d.setdefault(item[0], []).append(item[1])
... 
>>> d
{'88': ['TP'], '77': ['HK', 'KH'], '10': ['KB', 'BK', 'KB', 'KB']}
>>> {k: dict(Counter(v)) for k, v in d.items()}
{'88': {'TP': 1}, '77': {'HK': 1, 'KH': 1}, '10': {'KB': 3, 'BK': 1}}
下面是一个方法:

num=['10', '10', '10', '88', '77', '77', '10']
typ=['KB', 'BK', 'KB', 'TP', 'HK', 'KH', 'KB']

di={}

for i in range(len(num)):
    if num[i] not in di:
        di[num[i]]={}     
    if typ[i] not in di[num[i]]:
        di[num[i]][typ[i]] = 1
    else:
        di[num[i]][typ[i]] += 1

首先,正确地起草你的要求/问题,你会发现你的错误。另外,这个问题可能会被否决。你只需检查你的内部字典中是否存在密钥,不能将+=1添加到No key…@mootmoot-你说的“正确”是什么意思?如果他们做得不“正确”,他们可能会使用一个指针来指示如何做。我觉得很好。尽量不要无缘无故地消极,也不要没有建设性的反馈。IMHO,避免cargo cult编程(又名C&P)的最佳方法,就是将问题和规范澄清@埃斯卡耶夫给出了最好的答案,因为。我defaultdict是必需的。二,。当在dict中分配dict时,您必须将值分配给内部级别,即.get()进入图片。我添加我的投票,因为这是eskaev的备选答案。解释字典分配的问题。@mootmoot:我已经编辑过了。是否有任何可能不清楚的地方?