[英]Creating a dictionary from a list
From this list of tuples: 从此元组列表中:
[('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]
I want to create a dictionary, which keys will be [0]
and [1]
value of every third tuple . 我想创建一个字典,其键将是每三个元组的
[0]
和[1]
值。 Thus, the first key of dict created should be 'IND, MIA'
, second key 'LAA, SUN'
因此,创建的dict的第一把钥匙应该是
'IND, MIA'
,第二把钥匙'LAA, SUN'
The final result should be: 最终结果应为:
{'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')],\
'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]}
If this is of any relevance, once the values in question becomes keys, they may be removed from tuple, since then I do not need them anymore. 如果这有任何关系,则一旦所讨论的值成为键,就可以将它们从元组中删除,因为从那以后我就不再需要它们了。 Any suggestions greatly appreciated!
任何建议,不胜感激!
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 comprehension solution is possible, but somewhat messy. Dict理解解决方案是可能的,但有些混乱。
To remove keys from array replace second loop line ( result[item[0]+ ...
) with 要从数组中删除键,请将第二条循环线(
result[item[0]+ ...
)替换为
result[item[0]+","+item[1]] = [item[2:]]+inp[i+1:i+3]
Dict comprehension solution (a bit less messy than I initially thought :)) Dict理解解决方案(比我最初想象的要混乱的多:)
rslt = {
inp[i][0]+", "+inp[i][1]: inp[i:i+3]
for i in range(0, len(inp), 3)
}
And to add more kosher stuff into the answer, here's some useful links :): defaultdict , dict comprehensions 并在答案中添加更多犹太洁食,这是一些有用的链接:): defaultdict , dict comprehensions
Using the itertools
grouper
recipe : 使用
itertools
grouper
配方 :
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)}
should do it. 应该这样做。
The grouper()
method gives us groups of 3 tuples at a time. grouper()
方法一次为我们提供了3个元组的组。
Removing the key values from the dictionary values too: 也从字典值中删除键值:
{', '.join(g[0][:2]): (g[0][2:],) + g[1:] for g in grouper(inputlist, 3)}
Demo on your input: 您输入的演示:
>>> 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'))}
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)
output: 输出:
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')]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.