我有一个for循环,它给了我多个包含2个值的列表。这是for循环,数据取自excel文件。 当我想在字典中添加一个键已经存在的值时,问题就出现了
obj={}
test = ['Tonya Baker - Designer - noemail', ' Jess Huang - Designer - noemail', ' Denise Leung - Bizdev - noemail', ' Kristin Saulsbury - Bizdev - noemail', ' Molly Murphy - Bizdev - noemail', ' Angela Wood - Support - noemail', ' Heather Bond - Support - noemail', ' Natalie Ruiz - Support - noemail', ' Ivan Torres - Software - noemail', ' Max Gordon - Software - noemail', ' Jon Skulski - Software - noemail', ' Peggy Lin - Engineering - noemail', ' Andy Mai - Engineering - noemail', ' Alex Battaglino - Engineering - noemail', ' Evan Marks - Other - noemail', ' August Flanagan - Other - noemail', ' Helen Chi - Other - noemail', ' Ian Pearce - Other - noemail', ' Lisa Lamb - Marketing - noemail', ' Kate Levy - Marketing - noemail', ' Queen Tuba - Marketing - noemail', ' Crystal Baik - Marketing - noemail', ' Melissa Grant - Director - noemail', ' Scott Halcomb - Director - noemail', '
Victoria McCulloh - Manager - noemail', ' Shawn Warehouse - Manager - noemail', ' Shawn Norwood - Manager - noemail', ' Alex Bronson - Manager - noemail', ' Noah Solnick - Manager - noemail', ' Natalie Gordon - Csuite - noemail']
for i in test:
arr = i.lstrip(' ').rstrip(' ').split(' - ')
if arr[2] == 'noemail':
arr = arr[:2]
print(arr)
# gives multiple arrays [['Tonya Baker', 'Designer'], ['Jess Huang', 'Designer']]
obj[arr[1]] = arr[0]
print(obj) # {'Designer': ['Jess Huang']}
但我希望它是这样的:
{'Designer': ['Tonya Baker' ,'Jess Huang']}
使用
defaultdict
你可以用itertools.groupby来理解字典
输出:
您可以尝试以下方法:
我们只是在每次检查
obj
(dict)中是否已经存在我们现在正在获取的密钥,如果没有,我们将创建它,然后我们将添加该列表相关问题 更多 >
编程相关推荐