Given a dictionary in Python:  {u'100': 0, u'200': 1, u'300': 2, u'100': 1, u'400': 1, u'400': 1, u'500': 1}  How can I create a new dictionary that reverses the key and value:  {0: [u'100'], 1: [u'200', u'100', u'400', u'400', u'500'], 2: [u'100']}
4615
Given a dictionary like so:  my_map = {'a': 1, 'b': 2}   How can one invert this map to get:  inv_map = {1: 'a', 2: 'b'}
1436
Imagine that you have the following list. keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam']  What is the simplest way to produce the following dictionary? a_dict = {'name': 'Monty', 'age': 42, 'food': 'spam'}
91340
I need to obtain, for each feature of a layer, a dictionary with the attribute names and their values using PyQGIS. I can get all the attributes of the layer using indiv = QgsProject.instance().mapLayersByName('Individuos')[0]  for feature in features:     value = feature[field.name()]     attrs = feature.attributes()     print(attrs)  But what I need is to create a dictionary with field names as key and their value for each feature.
10523
I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
99659
I'd like to split strings like these  'foofo21' 'bar432' 'foobar12345'   into  ['foofo', '21'] ['bar', '432'] ['foobar', '12345']   Does somebody know an easy and simple way to do this in python?
13706
The canonical way to return multiple values in languages that support it is often . Option: Using a tuple Consider this trivial example: def f(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return (y0, y1, y2)  However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them. Option: Using a dictionary The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a dict. Consider the following: def g(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return {'y0': y0, 'y1': y1 ,'y2': y2}  (Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.) Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, result['y0']  Option: Using a class However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes: class ReturnValue:   def __init__(self, y0, y1, y2):      self.y0 = y0      self.y1 = y1      self.y2 = y2  def g(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return ReturnValue(y0, y1, y2)  In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue. There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as: class ReturnValue(object):   __slots__ = [&quot;y0&quot;, &quot;y1&quot;, &quot;y2&quot;]   def __init__(self, y0, y1, y2):      self.y0 = y0      self.y1 = y1      self.y2 = y2  From the :  The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.  Option: Using a  (Python 3.7+) Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools: @dataclass class Returnvalue:     y0: int     y1: float     y3: int  def total_cost(x):     y0 = x + 1     y1 = x * 3     y2 = y0 ** y3     return ReturnValue(y0, y1, y2)  Option: Using a list Another suggestion which I'd overlooked comes from Bill the Lizard: def h(x):   result = [x + 1]   result.append(x * 3)   result.append(y0 ** y3)   return result  This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are , whereas tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types. Question After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?
28573
I want to make an enumerated list in the following format:  [1] foo foo [2] foo foo ...    How I can do that using enumerated lists? I have tried the following:  \begin{enumerate}[\left[ 1 \right]]   but it does not work.
112773
I need to be able to take a string like:  '''foo, bar, "one, two", three four'''   into:  ['foo', 'bar', 'one, two', 'three four']   I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
2818
I know in JavaScript, objects double as hashes, but I have been unable to find a built-in function to get the keys: var h = {a:'b', c:'d'};  I want something like var k = h.keys() ; // k = ['a', 'c'];  It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that? I keep feeling it must be a simple built in function that I missed but I can't find it!
4570
I'd like to call a function in python using a dictionary.  Here is some code:  d = dict(param='test')  def f(param):     print(param)  f(d)   This prints {'param': 'test'} but I'd like it to just print test.  I'd like it to work similarly for more parameters:  d = dict(p1=1, p2=2) def f2(p1, p2):     print(p1, p2) f2(d)   Is this possible?
63309
I just saw this behaviour and I'm a bit surprised by it...  If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.  The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)  What am I missing here? Is this a behaviour I can count on?  EDIT: OK, I thought already of many of the reasons why this might happen (like the separate list to entries, whether this is a coincidence, etc). My question is, does anyone know how this really works?
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?
2998
I would like to encode some data with a key, and send it to a third party. They don't know the key to decode it, but I would like to make it possible for them to apply some modifications on it. Then they send i back, I can get decode it, and get the result. For example let the encoded data is the integer 5. I encode it with a key k and it becomes xxxxxx. The user can apply operations to xxxxxx without knowing k, like +5 and *2. After those operaions, the encoded value becomes yyyyyy. If I decode the value with the key k, it should be 20, as if I applied +5 and *2 on the original data 5. Are there any cryptographic algorithms like that?
59203
I have a the following dictionary:  IDictionary&lt;int, IList&lt;MyClass&gt;&gt; myDictionary    and I am wanting to get all the values in the dictionary as an IList....    Just to add a bit of a background as to how I've gotten into this situation....  I have a method that gets me a list of MyClass. I then have another method that converts that list into a dictionary where they key is the id for MyClass. Later on...and without access to that original list...I'm needing to obtain the original ungrouped list of MyClass.    When I pass myDictionary.Values.ToList() to a method that takes an IList I get a compile error that says that it can't convert from   System.Collections.Generic.List&lt;System.Collections.Generic.IList&lt;MyClass&gt;&gt;    to:  System.Collections.Generic.IList&lt;MyClass&gt;   Now, I can understand that its gone and added each of the groups of IList to the new list as separate elements of the list....but in this instance its not really what I'm after. I just want a list of all the values in the entire dictionary.  How then can I get what I'm after without looping through each of the key values in the dictionary and creating the list I want?
1551
What is a Pythonic way to pad a numeric string with zeroes to the left, i.e. so the numeric string has a specific length?
30124
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
10314
The indexer into Dictionary throws an exception if the key is missing.  Is there an implementation of IDictionary that instead will return default(T)? I know about the TryGetValue() method, but that's impossible to use with LINQ. Would this efficiently do what I need?: myDict.FirstOrDefault(a =&gt; a.Key == someKeyKalue);  I don't think it will as I think it will iterate the keys instead of using a Hash lookup.