从列表中创建字典

时间:2013-05-31 20:13:41

标签: python list dictionary

从这个元组列表中:

[('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')] 

我想创建一个字典,其中每个第三元组的键值为[0][1] 。因此,创建的dict的第一个键应该是'IND, MIA',第二个键'LAA, SUN'

最终结果应为:

{'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')],\
'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]}

如果这是相关的,一旦有问题的值成为键,它们就可以从元组中删除,因为那时我不再需要它们了。任何建议都非常感谢!

3 个答案:

答案 0 :(得分:4)

inp = [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
       ('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]

result = {}
for i in range(0, len(inp), 3):
    item = inp[i]
    result[item[0]+","+item[1]] = inp[i:i+3]

print (result)

Dict理解解决方案是可能的,但有些混乱。

从数组中删除键用

替换第二个循环线(result[item[0]+ ...
result[item[0]+","+item[1]] = [item[2:]]+inp[i+1:i+3]

Dict理解解决方案(比我最初想的要少一点:))

rslt = {
    inp[i][0]+", "+inp[i][1]: inp[i:i+3]
    for i in range(0, len(inp), 3)
}

要在答案中添加更多犹太教资料,这里有一些有用的链接:):defaultdictdict comprehensions

答案 1 :(得分:2)

使用itertools grouper recipe

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

{', '.join(g[0][:2]): g for g in grouper(inputlist, 3)}

应该这样做。

grouper()方法一次为我们提供3个元组。

从字典值中删除键值:

{', '.join(g[0][:2]): (g[0][2:],) + g[1:]  for g in grouper(inputlist, 3)}

您输入的演示:

>>> from pprint import pprint
>>> pprint({', '.join(g[0][:2]): g for g in grouper(inputlist, 3)})
{'IND, MIA': (('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')),
 'LAA, SUN': (('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}
>>> pprint({', '.join(g[0][:2]): (g[0][2:],) + g[1:]  for g in grouper(inputlist, 3)})
{'IND, MIA': (('05/30',), ('ND', '07/30'), ('UNA', 'ONA', '100')),
 'LAA, SUN': (('05/30',), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}

答案 2 :(得分:1)

from collections import defaultdict
def solve(lis, skip = 0):
    dic = defaultdict(list)
    it = iter(lis)                    # create an iterator
    for elem in it:
        key = ", ".join(elem[:2])     # create key
        dic[key].append(elem)
        for elem in xrange(skip):     # append the next two items to the 
            dic[key].append(next(it)) # dic as skip =2 
    print dic


solve([('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')], skip = 2)

<强>输出:

defaultdict(<type 'list'>,
 {'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')],
 'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')]
 })