Twilight0 Twilight0 - 26 days ago 11
Python Question

python: construct listed dictionaries according to a conditional for listed tuples

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' or 'Value4' in string1:
string4 = 'somevalue1'
elif 'Value7' or 'Value8' 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'.

Answer

I put all your pieces together and then everything worked

items = [('Value1','Value2','Value3'),('Value4','Value5','Value6'),('Value7','Value8','Value9')]
final_list = []

for string1, string2, string3 in items:
    if 'Value1' in string1:
        string4 = 'somevalue1'
    elif 'Value2' in string1:
        string4 = 'somevalue2'
    else:
        string4 = ''
    item_data = ({'key1': string1, 'key2': string2, 'key3': string3, 'key4': string4})
    final_list.append(item_data)

print final_list

Output:

[{'key4': 'somevalue1', 'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}, {'key4': '', 'key1': 'Value4', 'key2': 'Value5', 'key3': 'Value6'}, {'key4': '', 'key1': 'Value7', 'key2': 'Value8', 'key3': 'Value9'}]

UPDATE(Since you've updated question)

The problem with conditions

Because if 'Value1' or 'Value4' in string1: is equal to if ('Value1') or ('Value4' in string1): And this will always be True, because only empty string will be False

And so to make your code work, change condition block:

if string1 in ('Value1', 'Value4'):
    string4 = 'somevalue1'
elif string1 in ('Value7', 'Value8'):
    string4 = 'somevalue2'
else:
    string4 = ''