This list of tuples:
items = [('Value1','Value2','Value3'),('Value4','Value5','Value6'),('Value7','Value8','Value9')]
and I have made a "for" loop to make them listed dictionaries:
final_list = []
for string1, string2, string3 in items:
item_data = ({'key1': string1, 'key2': string2, 'key3': string3})
final_list.append(item_data)
print final_list
and result is this:
[{'key1': Value1, 'key2': Value2, 'key3': Value3},{'key1': Value4, 'key2': Value5, 'key3': Value6}...]
What I am trying to achieve is insert another key-value pair according to a conditional for the key1,value1(string1) pair.
I placed this conditional inside the for loop above:
if 'Value1' in string1:
string4 = 'somevalue1'
elif 'Value2' in string1:
string4 = 'somevalue2'
else:
string4 = ''
then construsted dictionary as below:
item_data = ({'key1': string1, 'key2': string2, 'key3': string3, 'key4': string4})
but I didn't get what I expected and instead it got this:
[{'key1': Value1, 'key2': Value2, 'key3': Value3, 'key4': 'somevalue1'},{'key1': Value4, 'key2': Value5, 'key3': Value6, 'key4': 'somevalue1'}...]
I was expecting key4's value to be filled according to the value of key1(string1) and with the above statements but doesn't check the next item. It persists with 'somevalue1'.
Aucun commentaire:
Enregistrer un commentaire