简体   繁体   English

遍历列表和字典

[英]Iterate over list and dict in parallel

I have a list that contains 5 variables, say: 我有一个包含5个变量的列表,说:

list2=[1,2,3,4,5] 

and I have a list of dict with 5 key-value pairs, which I initialized to be : 我有一个包含5个键值对的字典列表,我将其初始化为:

list1[i]= {"input1": 0, "input2": 0, "input3": 0, "input4": 0, "input5": 0}

I want to iterate over the dict and list so that in each iteration, I will replace the value of a key in the dict with the value from the list, so the dict will become: 我想遍历字典和列表,以便在每次迭代中,用列表中的值替换字典中键的值,因此字典将变为:

list1[i]= {"input1": 1, "input2": 2, "input3": 3, "input4": 4, "input5": 5}

Currently, I use this to iterate over the dict and list: 当前,我使用它来遍历字典和列表:

def Get_Param(self):
    self.list1=[]
    inputcount=0
    for line in self.textBox.get('1.0', 'end-1c').splitlines():
        if line:
            self.list1.append({'input1':0, 'input2':0, 'input3': 0, 'input4': 0, 'input5': 0})
            list2=[int(i) for i in line.split()]
            for parameter, value in zip(self.list1[inputcount], list2): //exception is thrown here
                self.list1[inputcount][parameter]=value
        inputcount+=1

but it keeps returning "list indices must be integers, not Unicode" exception. 但它始终返回“列表索引必须是整数,而不是Unicode”异常。 Can anyone suggest a better idea to do this or tell me in which part of the code I did wrong? 谁能建议一个更好的主意,或者告诉我我在代码的哪一部分做错了?

You can zip your dicts sorted keys with the list and produce a new dict . 您可以使用列表zip dicts排序键,并生成一个新dict That matches the numbers in the list and the dict. 匹配列表和字典中的数字。

>>> list2=[1,2,3,4,5]
>>> list1=[{"input1": 0, "input2": 0, "input3": 0, "input4": 0, "input5": 0}]
>>> dict(zip(sorted(list1[0].keys()), list2))
{'input4': 4, 'input1': 1, 'input5': 5, 'input2': 2, 'input3': 3}

The dict itself is not ordered but the indices match. 字典本身未排序,但索引匹配。 You dont actually even need the call to keys() . 您实际上甚至不需要调用keys() It will still work without it. 没有它,它仍然可以工作。

This shows how to build a single dict. 这显示了如何构建单个字典。 To create a list of them simply do this in a loop. 要创建它们的列表,只需循环执行即可。

You can reduce a lot of the extraneous code by simply creating two lists (keys and associated values), and using a dictionary comprehension to join them into your final dictionary. 您可以通过简单地创建两个列表(键和关联值),然后使用字典理解将它们加入最终字典中,从而减少大量无关代码。 This solves the issue of trying to map an ordered list onto an unordered dictionary. 这解决了尝试将有序列表映射到无序列字典的问题。

def Get_Param(self):
    self.list1 = []
    dict_keys = ['input1', 'input2', 'input3', 'input4', 'input5']
    for line in self.textBox.get('1.0', 'end-1c').splitlines():
        if line:
            list2 = [int(i) for i in line.split()]
            self.list1.append({key: value for key, value in zip(dict_keys, list2)})

You can refer this solution and customize to solve your problem: 您可以参考此解决方案并进行自定义以解决您的问题:

list1=[1,2,3,4,5] 
dict1= {"input1": 0, "input2": 0, "input3": 0, "input4": 0, "input5": 0}

d = {}
for i in dict1:
    d[i] = list1[int(i.replace("input",''))-1]
print d

Output : {'input2': 2, 'input3': 3, 'input1': 1, 'input4': 4, 'input5': 5} 输出:{'input2':2,'input3':3,'input1':1,'input4':4,'input5':5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM