assign value to a variable in a list in Python - python-3.x

I have a list of lists in the format
list = [["text1",index_value1],["text2",index_value2],["text3",index_value3]]
In a for loop I want to assign values to index_value1, index_value2, ...
If I do
list[0][1] = 5
I would replace index_value1 in the list with 5 instead assigning the value 5 to index_value1.
How can I assign the value to the variable instead of replacing the variable in the list.
I could change the list to
list = [["text1","index_value1"],["text2","index_value2"],["text3","index_value3"]]
If this simplifies the solution.
Thanks for any help

This is a workaround using Python dictionary, as you cannot assign a value to a variable in a list without declaring it first.
dict = {
0: {"id": "text1", "index_value1": None},
1: {"id": "text2", "index_value2": None},
2: {"id": "text3", "index_value3": None}
}
To assign a value:
dict[0]["index_value1"] = 5

How do you want a assign a variable like a array or an dictionary ? without that it replace the indexvalue variable with a value you provided.
index_value1 = None
index_value2 = None
index_value3 = None
list1 = [["text1", index_value1], ["text2", index_value2], ["text3", index_value3]]
for val in list1:
val[1] = 5
print(list1)

Related

Create Dictionary with name and value of list of variables

I have a list of variables in python. And I want to create a dictionary whose key will be the name of the variable and the value will be the content.
a,b,c = 1,2,3
list = [a,b,c]
dic = {f'{item=}'.split('=')[0]:item for item in list}
If I run the previous code, I get as result the following:
{'item': 3}
And i would like to get the following:
{'a':1,'b':2,'c':3}
Thanks in advance
One potential way of doing it is like so (see https://stackoverflow.com/a/592891/11530613):
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
d = {f'{namestr(i, globals())[0]}': i for i in list}
This gives:
{'a': 1, 'b': 2, 'c': 3}
This is definitely a bad idea though, especially with your toy example. For example, integers in Python are the same "object"—if I say:
a = 1
e = 1
a is e
I get True, even though I'm testing identity and not equality. So the moment I have another variable with the same value from your toy example above, the is test might evaluate to True, and you could get bad results. Case in point:
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
__ = 1
d = {f'{namestr(i, globals())[0]}': i for i in list}
yields
{'__': 1, 'b': 2, 'c': 3}
This is simply an explanation of how you could do it, not that you ever should do it this way. But if you had like, a very short notebook or something and you knew no other variables would ever overlap, you might hack it this way.

Is there a simpler way to extract the last value of a dictionary?

So I was tasked to make a function using python, that returns how many values there is in a dictionary that ONLY contains lists. An example of such a dictionary would be:
animals = { 'a': ['alpaca','ardvark'], 'b': ['baboon'], 'c': ['coati']}
The values inside the list also count towards the total values returned from the function, which means that it has to return 4. This is the function I made:
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
numValues = 0;
while aDict != {}:
tupKeyValue = aDict.popitem();
List = tupKeyValue[1];
numValues += len(List);
return numValues;
So I was wondering if there was a way to pop the last value of a dictionary without popitem() which extracts the key-value pair. Just trying to make it as simple as possible.
Since you are not using the dictionaries keys maybe you could just use values() along with sum():
def how_many(d):
return sum(len(v) for v in d.values())
animals = {'a': ['alpaca', 'ardvark'], 'b': ['baboon'], 'c': ['coati']}
print(how_many(animals))
Output:
4

Extracting lists from the lists of lists and assigning them into columns in python

I have a dataset(df_norm) with a column 'geometry.coordinates' that has a list of lists(l1) as it's value:
geometry.coordinates
0 [[[23.514690935490876, 53.946715071429367], [2...
1 [[[23.549827385369554, 53.942282407709513], [2...
2 [[[23.574999999999307, 53.941666666666151], [2...
I need to extract the individual coordinates from each list and assign each coordinate into a separate column, to get the output similar to this:
longitude1 latitude1 longitude2 latitude2 ...
23.514690935490876 53.946715071429367 23.5127605166679412 53.961345695020002
23.549827385369554 53.942282407709513 23.6123409888603434 53.941666666666151
....
The code I have is:
def flatten_list(l1):
flat_list = []
for sublist in df_norm['geometry.coordinates'][0]:
for item in sublist:
flat_list.append(item)
return flat_list
for i in range(len(df_norm['geometry.coordinates'])):
for j in df_norm['geometry.coordinates']:
flatten_list(df_norm['geometry.coordinates'])
var1 = flat_list[i][0]
var2 = flat_list[i][1]
var3 = flat_list[i][2]
var4 = flat_list[i][3]
var5 = flat_list[i][4]
I get an error:
IndexError: list index out of range
What am I doing wrong?
It seems your flatten_list() function produces a single un-nested list of all your values. However, when you index the list to assign the variables, you are using a nested notation flat_list[i][0].
In order to distribute the values from your new list produced by flatten_list() to the corresponding variables, try changing the indices as such:
for i in range(len(df_norm['geometry.coordinates'])):
for j in df_norm['geometry.coordinates']:
flatten_list(df_norm['geometry.coordinates'])
var1 = flat_list[i]
var2 = flat_list[i+1]
var3 = flat_list[i+2]
var4 = flat_list[i+3]
var5 = flat_list[i+4]
Further, if I understand your goal correctly, you want to produce lists under each of these variable names. As is, the loop will replace the values and only leave the final 5 values saved (one as each of the variables). Perhaps producing lists for each variable outside the loop and appending the values would be a better approach? Finally - a change to your range() parameters might be needed. Otherwise, duplicate values corresponding to one variable will be placed in the wrong variable as the temporary i variable progresses.
var1 = []
var2 = []
var3 = []
var4 = []
var5 = []
for i in range(0,len(df_norm['geometry.coordinates'],5)):
for j in df_norm['geometry.coordinates']:
flatten_list(df_norm['geometry.coordinates'])
var1.append(flat_list[i])
var2.append(flat_list[i+1])
var3.append(flat_list[i+2])
var4.append(flat_list[i+3])
var5.append(flat_list[i+4])
You got the error could be probably because you don't assign the value returned by the function.

Convert elements in ONE list to keys and values in a dictionary

I'm looking for a way to convert a list to a dictionary as shown below. Is this possible? Thanks in advance.
list = ["1/a", "2/b", "3/c"]
dict = {"1": "a", "2": "b", "3": "c"}
Of course it is possible.
First, you can split an element of the list with e.split("/"), which will give a list for example splitted = ["1", "a"].
You can assign the first element to the key and the second to the value:
k = splitted[0]
v = splitted[1]
or another way to express that:
k,v = splitted
Then you can iterate over your list to build your dict, so if we wrap this up (you should not call a list list because list is a type and an already existing identifier:
d = {}
for e in elements:
k,v = e.split("/")
d[k] = v
You can also do that in one line with a dict comprehension:
d = {k:v for k,v in [e.split("/") for e in elements]}
Yes you can.
If you want to have everything after the '/' (i.e. 2nd char), you can do:
dict = {c[0]:c[2:] for c in list}
If you want to have everything after the '/' (but may not be the 2nd char), you can do:
dict = {c[0]:c.split('/')[1] for c in list}
It really dependes on the input you have and what output you want
You can do like this.
lista = ["1/a", "2/b", "3/c"]
new_dict = {}
for val in lista:
new_dict.update({val[0]:val[2]})
print(new_dict)
Try this
list = ["1as/aasc", "2sa/bef", "3edc/cadeef"]
dict = {i.split('/')[0]:i.split('/')[1] for i in list}
Answer will be
{'1as': 'aasc', '2sa': 'bef', '3edc': 'cadeef'}
I have given a different test case. Hope this will answer your question.

python3 value returned wrong with container variable

I meet a code that failed to meet my expectation. Details as below:
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
Dict = {}
c = []
for i in range(0,3):
for j in range(0,1):
Dict[a[j]] = b[i][j]
c.append(Dict)
print(c)
>>> [{'name':'name=pan'},{'name':'name=pan'},{'name':'name=pan'}]
what i expected should be
>>> [{'name':'name=cheng'},{'name':'name=huang'},{'name':'name=pan'}]
So could you please tell me how to solve the issue ?
You are changing the value of Dict in place and not creating a new dictionary every time. Each iteration of the loop, you are setting Dict["name"] equal to one of the elements in b and then appending it to the list. The next iteration of your loop changes dict in place (meaning the previous version you appending to c will also be changed). The result is that your list c is filled with 3 exact copies (exact same location in memory) of the dictionary created in the final iteration of the loop.
How do you fix this? Make a new dictionary every time.
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
c = []
for i in range(0,3):
for j in range(0,1):
temp_dict = {a[j]: b[i][j]}
c.append(temp_dict)
print(c)
Result:
[{'name': 'name=cheng'}, {'name': 'name=huang'}, {'name': 'name=pan'}]
You use the same value of Dict for all of the iterations of the loop. So all of the dictionaries are the same. You just have three copies of the same dictionary in the list.
If you move the Dict = {} statement into the loop, it will be fixed.
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
c = []
for i in range(0,3):
Dict = {}
for j in range(0,1):
Dict[a[j]] = b[i][j]
c.append(Dict)
print(c)
Or more Pythonic:
keys = ['name']
values_list = [('name=cheng',), ('name=huang',), ('name=pan',)]
result = []
for values in values_list:
result.append(dict(zip(keys, values)))
print(result)
This works by using the zip builtin which does the same thing as [(x[i], y[i]) for i in range(min(len(x), len(y))] without needing to keep track of the indices or lengths.
The dict class can build a dictionary from a list of tuples, which is what this solution uses.

Resources