当我使用zip函数从下面的两个列表创建字典时,并非所有键值对都存储在字典中
>>> selfips=['1.0.0.1', '165.1.4.5', '165.3.4.5', '165.3.4.4', '165.3.4.4']
>>> statefloatingselfips=['STATE_DISABLED', 'STATE_DISABLED', 'STATE_DISABLED', 'STATE_ENABLED', 'STATE_ENABLED']
>>> floatdict=dict(zip(statefloatingselfips, selfips))
>>> print floatdict
{'STATE_ENABLED': '165.3.4.4', 'STATE_DISABLED': '165.3.4.5'}
答案 0 :(得分:3)
由于字典的键是唯一的,您可以使用collections.defaultdict
执行此类任务:
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for i,j in zip(statefloatingselfips, selfips):
... d[i].append(j)
...
>>> d
defaultdict(<type 'list'>, {'STATE_ENABLED': ['165.3.4.4', '165.3.4.4'], 'STATE_DISABLED': ['1.0.0.1', '165.1.4.5', '165.3.4.5']})
>>>
答案 1 :(得分:2)
您可能有字典 - 州:地址列表
map_by_state = collections.defaultdict(list)
for state, address in zip (statefloatingselfips, selfips):
map_by_state[state].append(address)
答案 2 :(得分:1)
您不能拥有具有相似值的多个键。相反,您可以使用defaultdict
制作共享状态的所有ips中的set
:
from collections import defaultdict
d = defaultdict(set)
selfips=['1.0.0.1', '165.1.4.5', '165.3.4.5', '165.3.4.4', '165.3.4.4']
statefloatingselfips=[
'STATE_DISABLED', 'STATE_DISABLED', 'STATE_DISABLED',
'STATE_ENABLED', 'STATE_ENABLED'
]
for ip, state in zip(selfips, statefloatingselfips):
d[state].add(ip)
print d
输出:
defaultdict(<type 'set'>, {
'STATE_ENABLED': set(['165.3.4.4']),
'STATE_DISABLED': set(['1.0.0.1', '165.3.4.5', '165.1.4.5'])
})