I am formatting a dictionary like so: for index, team_id in dataframe.get('team_id').items():     format_redis[str(team_id)] = {                 'x': float(dataframe['x'][index]),                 'y': float(dataframe['y'][index]),                 'z': float(dataframe['z'][index]),                 'n': float(dataframe['n'][index])             }  Now I'd like to pass a condition for adding the value, like: ...  {'x': float(dataframe['x'][index]) if str(dataframe['home'][index] == 'home',  'y': float(dataframe['y'][index]) if str(dataframe['home'][index] == 'away'}   But this syntax is not valid. Which one is the right one?
852
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
5832
I want to write a function in Python that returns different fixed values based on the value of an input index.    In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?
83114
In ArcGIS 10.5, I am building a model that should convert a field of coded values to another code. This seems like it should be a simple if/then statement but I am not getting it. To simplify the process, I populated the target field with the source field's values and then intend on using python to transpose the values. It should be considered a string, but the values are numerical. The field I am trying to edit is "TP_Condi"   In the "Calculate Field" code block:  def reclass:   if TP_Condi = 3:          return 1     elif TP_Condi = 2:           return 8   elif TP_Condi = 1:          return 3   else:          return "error"      This is the code I was seeking:
106
I need a good explanation (references are a plus) on Python's slice notation.   To me, this notation needs a bit of picking up.   It looks extremely powerful, but I haven't quite got my head around it.
2368
It seems like there should be a simpler way than:  import string s = "string. With. Punctuation?" # Sample string  out = s.translate(string.maketrans("",""), string.punctuation)   Is there?
16116
When using IF statements in Python, you have to do the following to make the "cascade" work correctly.  if job == "mechanic" or job == "tech":         print "awesome" elif job == "tool" or job == "rock":         print "dolt"   Is there a way to make Python accept multiple values when checking for "equals to"? For example,  if job == "mechanic" or "tech":     print "awesome" elif job == "tool" or "rock":     print "dolt"
27093
I occasionally see the list slice syntax used in Python code like this:  newList = oldList[:]   Surely this is just the same as:  newList = oldList   Or am I missing something?
55449
I am trying to access a bool property in the python API to see if an option is enabled or not. The python tooltip for the option says this:  bpy.data.screens['Default']...show_grease_pencil   I try to use that in the console or in py scripts, and it says the ellipsis(...) is invalid syntax. What am I missing? (Ignore the tooltip text. I originally thought the '...' was just hiding some of the API). I tried it with double quotes and that didn't help.
32175
I feel really stupid for asking this, but how do you form more complex if conditionals in TeX? I'm looking for something like:  \ifnum\x=1 OR \ifnum\x=14     {do this} \else     {do that} \fi   I don't want to have to resort to copy-pasting the entire condition just to change the expression when the body is the same.
54174
From my thesis:     In this method, the get_config_value function is used that is defined within the PyWPS API.   How should I format the "get_config_value" variable?  It should be formatted differently than the rest of the text, but I don't know what the conventions are.  Using italic or bold fonts doesn't look right to me.
2534
I am trying to calculate field test2 with only the numeric values from a string field test. The entire script is like:    def makestr(test)      list=[]      for s in test:          if s.isdigit():              list.append(s)      for a in list:          str=''.join(list)     But I keep getting an error:    Any ideas?
556
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union).  The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place. &gt;&gt;&gt; x = {'a': 1, 'b': 2} &gt;&gt;&gt; y = {'b': 10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print(z) None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11}  How can I get that final merged dictionary in z, not x? (To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
4991
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.  I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:  for item in self.inventory_names:     self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)     self.cursor.close()   I get the error:     sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.   I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.  cursor.execute("""CREATE TABLE Equipment      (id INTEGER PRIMARY KEY,      name TEXT,     price INTEGER,      weight REAL,      info TEXT,      ammo_cap INTEGER,      availability_west TEXT,     availability_east TEXT)""")   However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:  for item in self.inventory_names:     self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)     self.cursor.close()   I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?
15003
Can you add new statements (like print, raise, with) to Python's syntax?  Say, to allow..  mystatement "Something"   Or,  new_if True:     print "example"   Not so much if you should, but rather if it's possible (short of modifying the python interpreters code)
22907
I have a CSV file I open as a DataFrame. Among the columns is one named geom 1 :  df.loc[:, 'geom 1'] &gt;&gt;&gt; 0       {'type': 'Polygon', 'coordinates': [[[2.826589... 1       {'type': 'Polygon', 'coordinates': [[[2.225689... 2       {'type': 'Polygon', 'coordinates': [[[2.225689... 3       {'type': 'MultiPolygon', 'coordinates': [[[[5.... 4       {'type': 'Polygon', 'coordinates': [[[3.933055...                               ...                         2998                                                 None 2999                                                  NaN 3000    {'type': 'Polygon', 'coordinates': [[[5.014937... 3001    {'type': 'Polygon', 'coordinates': [[[4.912995... 3002    {'type': 'Polygon', 'coordinates': [[[4.739631... Name: geom 1, Length: 3003, dtype: object  #Conditionning the dataframe : df.replace('None', np.nan, inplace=True)   I would like to convert these strings to geometries in a GeoDataFrame.   After a few resarches I did not find a working solution :   :  df.loc[:, 'geom 1'] = df.loc[:, 'geom 1'].apply(wkt.loads)  &gt;&gt;&gt; ParseException: Unknown type: '{'TYPE':' WKTReadingError: Could not create geometry because of errors while reading input.    :  df.replace('None', np.nan, inplace=True) geom = [shape(i) for i in df.loc[:, 'geom 1'].dropna()] &gt;&gt;&gt; AttributeError: 'str' object has no attribute 'get'   What I succeded was to sent the DataFrame to PostGIS, convert the type of the column geom 1 from text to geometry and use the function ST_FromGeoJson to access the geometry. Since I have many columns geom I want to do this under python in order to merge all the columns geom into a single one named all_geoms.
72972
I have this pgfplots code that I want to put in a lstlisting environment:  \pgfplotsset{    every axis x label/.append style = {       font = \small    },    every axis y label/.append style = {       font = \small,       rotate = -90,       xshift = 0.5em    } }   How can I convince the listings package that those strings like every axis x label have to be treated as identifiers? I don't like the idea of assigning the role of keyword to the single substrings every, axis, x, label.