I'm playing with some loops in python. I am quite familiar with using the "for" loop:
for x in y:
do something
You can also create a simple list using a loop:
i = []
for x in y:
i.append(x)
and then I recently discovered a nice efficient type of loop, here on Stack, to build a list (is there a name for this type of loop? I'd really like to know so I can search on it a little better):
[x.name for x in y]
Ok, that being said, I wanted to go further with the last type of loop and I tried to build a python dictionary using the same type of logic:
{x[row.SITE_NAME] = row.LOOKUP_TABLE for row in cursor}
instead of using:
x = {}
for row in cursor:
x[row.SITE_NAME] = row.LOOKUP_TABLE
I get an error message on the equal sign telling me it's an invalid syntax. I believe in this case, it's basically telling me that equal sign is a conditional clause (==), not a declaration of a variable.
My second question is, can I build a python dictionary using this type of loop or am I way off base? If so, how would I structure it?
The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.):
x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor }
so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want to add to this key in the dictionary:
{ _key : _value(_key) for _key in _container }
What you're using is called a list comprehension. They're pretty awesome ;)
They have a cousin called a generator expression that works like a list comprehension but instead of building the list all at once, they generate one item at a time. Hence the name generator. You can even build functions that are generators - there are plenty of questions and sites to cover that info, though.
You can do one of two things:
x = dict(((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor))
Or, if you have a sufficiently new version of Python, there is something called a dictionary comprehension - which works like a list comprehension, but produces a dictionary instead.
x = {row.SITE_NAME : row.LOOKUP_TABLE for row in cursor}
You can do it like this:
x = dict((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor)
Related
As I was studying Python, I came across this task:
Imagine Python did not have built-in support for sets. Show how we
could use dictionaries to represent sets. Write the four set
operations | - ^ & for this new representation of sets.
Below you can see the answer:
First, for the ‘or’ operation, we add entries to the new dictionary
from both input lists:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
def t_or(l1,l2):
result = {}
for x in l1: result[x] = 0
for x in l2: result[x] = 0
print(result)
So, I'm wondering why have the author used such a strange method to add entries result[x] = 0? Isn't there a better way to do it, maybe using alternatives methods like .add, .insert, etc?
result[key] = value is the way to assign a new pair key:value in a Python dictionary. You don't have to create the entry key first on a Dictionary. If you come from Java, for example, the syntaxis is like:
Map<String, String> result = new HashMap<int, int>();
result.put(1, 0);
As you can see, on Java you are not declaring the key too, the same happens on a lot of languages and that is because of how a dictionary key works.
When you want to retrieve an element from a dictionary, you have to be sure that the key already exists in the dictionary, otherwise it will throw an exception.
The .add or .insert that you have in mind in Python is .append and it is used to add a new element to a list:
my_list = []
my_list.append(0)
So no, there is no a better way or a different way to assign new key:value pairs on a Python dictionary.
I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.
for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call
https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.
EDIT:
for i,j in enumerate(dict1.keys()): j = somethingElse
EDIT2:
I think the problem may be with pandas. The first line works, not the second.
for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])
EDIT3:
That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:
for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])
EDIT4:
According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:
listOfFrame = []
for j in dict.keys():
j = pd.DataFrame(dict[j]['Values'])
listOfFrame.append(j)
Indeed j will be a str (or whatever else type of key you are using in dict).
The actual problem is with the loop body, as the error message states:
str(j) = somethingElse
is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.
Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:
dfs = []
for val in dict1.values():
dfs.append(pd.DataFrame(val['Values']))
However, this would normally written without an explicit loop in Python, for instance by using list comprehension:
dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]
From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Please let me know how this for loop is working.
points = {0,1,2,3,4,8,1}
x = float(sum([len(points) for i in points]))
print(x)
This code snippet is giving me output as:-
36.0
List comprehensions are not that hard if you take a look at a very simple example:
[T(x) for x in X]
The first term is declaring what should be done with all the individual items in the collection we are iterating over. This might be type conversion or just extracting a specific value from a dict.
The symbol after the for just defines the name for our iteration variable and the last term is the collection(list, set, dict etc.) which we iterate through.
A more verbose implementation of the same thing could be:
result = []
for i in range(len(X)):
result.append(T(X[i]))
After this the content of result is the same as the list returned by the list comprehension.
I am a beginner in Python and kindly I have a question: Given the following:
np.asarray([self.simulate(c) for c in challenges])
I want to break it down to look familiar in the traditional coding way. Can I say it is equivalent to:
for c in challenges:
y = self.simulate(c)
y = np.asarray[y]
Thank you.
It's not called "pythonic looping", but list comprehension.
The equivalent would be:
items = []
for c in challenges:
items.append(self.simulate(c))
nparr = np.asarray(items)
The problem with your method is that you're are not building a list, such as this list comprehension does. Rather, you are simply indexing one item from np.asarray, and never saving the value. Furthermore, you don't even want to be indexing np.asarray, you want to pass a list to its constructor.
You need to create a temporary list to hold the return value of self.simulate(c) on each iteration of challenges and pass that list to np.asarray:
temp = []
for c in challenges:
temp.append(self.simulate(c))
array = np.asarray(temp)
Also, just to let you know, the "pythonic loop" you're referring to is usually called a list comprehension. "Pythonic" is just a name us Python community members use to describe something that is idiomatic to the Python language and its ideals.
New to python, trying to figure out how to replace words using a dict.
It is setup like:
list = {"word1":"word2",
"word3":"word4",
"word5":"word6"
}
I have :
for w in list:
new_list = old_list.replace(w)
Thanks!
As pointed out in the comment, list is a built-in name, and you have overwritten it - this might cause weird behaviour.
Your syntax for creating the dictionary is correct, but let's call it my_dict.
Now what are you trying to do? Your title suggets, that you want to replace substrings and not elements in lists?
Anyway, the for-loop loops over the keys of the dictionary. So inside it you should do my_string.replace(my_dict, my_dict[w])
Alternatively, you can loop over the key-value-pairs: for k, v in my_dict.items(). Inside this loop you can use my_string.replace(k, v)