Reza
Reza

Reputation: 25

Iterate over list and dict in parallel

I have a list that contains 5 variables, say:

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

and I have a list of dict with 5 key-value pairs, which I initialized to be :

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. Can anyone suggest a better idea to do this or tell me in which part of the code I did wrong?

Upvotes: 1

Views: 2693

Answers (3)

Pradip Das
Pradip Das

Reputation: 738

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}

Upvotes: -1

Andrew Guy
Andrew Guy

Reputation: 10008

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)})

Upvotes: 2

Paul Rooney
Paul Rooney

Reputation: 21619

You can zip your dicts sorted keys with the list and produce a new 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(). 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.

Upvotes: 0

Related Questions