如何将两个列表按顺序组合成字典?

时间:2018-03-03 08:41:58

标签: python python-3.x dictionary

我正在尝试将两个列表的值组合成单个字典集但是在组合词典之后键和值没有按列表中的原始顺序排列,它与随机键和值配对,那么如何将它们按顺序组合?请参阅下面的输入和输出:

data_ids = ['22630876', '22626950', '22624826', '22626159', '22616496', '22601480', '22611197', '22600498', '22605808', '22602601', '22602543', '22594071', '22595982', '22593725', '22591441', '22553315', '22584758']



tag_ids = ['WATCH - Stokes faces unpredictable balls', "'Bad position, but we're not out of it' - de Villiers", 'Who is Sandeep Lamichhane?', 'WATCH - All the action from the Super Over', "WATCH - Sammy's four-ball blitz", "Shubman Gill's red-hot run streak", 'Should bowlers start wearing helmets?', 'Keshav Maharaj could be key - Graeme Smith', "WATCH - Kevin Pietersen's match-winning 48", "'It was emotional walking off the pitch' - Stokes", "WATCH - India's gains from the South Africa tour", 'WATCH - Best of Kohli in South Africa', 'The Ashwin-Gibbs exchange: funny, or not?', "Mayank Agarwal's incredible run of domestic form", "'SA can't afford spicy pitches against Australia'", 'Ice Cricket: Legends play T20 in the Alps', 'Dhoni, Kohli and quirky on-field  chatter']


z = dict(zip(data_ids,tag_ids))

print(z)



{'22595982': 'The Ashwin-Gibbs exchange: funny, or not?', '22593725': "Mayank Agarwal's incredible run of domestic form", '22626159': 'WATCH - All the action from the Super Over', '22553315': 'Ice Cricket: Legends play T20 in the Alps', '22626950': "'Bad position, but we're not out of it' - de Villiers", '22624826': 'Who is Sandeep Lamichhane?', '22611197': 'Should bowlers start wearing helmets?', '22630876': 'WATCH - Stokes faces unpredictable balls', '22600498': 'Keshav Maharaj could be key - Graeme Smith', '22602601': "'It was emotional walking off the pitch' - Stokes", '22602543': "WATCH - India's gains from the South Africa tour", '22591441': "'SA can't afford spicy pitches against Australia'", '22601480': "Shubman Gill's red-hot run streak", '22594071': 'WATCH - Best of Kohli in South Africa', '22605808': "WATCH - Kevin Pietersen's match-winning 48", '22584758': 'Dhoni, Kohli and quirky on-field  chatter', '22616496': "WATCH - Sammy's four-ball blitz"}

你可以看到z的输出以键值'22595982'开头但它应该是'22630876',甚至与字典值相同,我怎么能这样做,我搜索了类似的问题,但我没有找到任何

3 个答案:

答案 0 :(得分:3)

使用默认dict时,即使碰巧符合某些期望,也不应依赖于元素的顺序。有一个专用的字典实现,它保持插入顺序,从2.7:

开始
class collections.OrderedDict([items])
  

返回一个dict子类的实例,支持通常的dict方法。 OrderedDict是一个dict,它记住了第一次插入键的顺序。如果新条目覆盖现有条目,则原始插入位置保持不变。删除一个条目并重新插入它将把它移到最后。

答案 1 :(得分:2)

试试这个,我猜这将是你的答案。

<div class="wrapper">
  <div class="box">box 1</div>
  <div class="box">box 2</div>
  <div class="box">box 3</div>
</div>

输出:

from collections import OrderedDict

d = OrderedDict(zip(data_ids, tag_ids))
for i, j in d.items():
    print(i)
    print(j)

答案 2 :(得分:0)

由于列表是有序集合,因此对我有用:

mydict = dict(zip(list1, list2))