Rectangle 27 39

Why doesn't Python offer it out of the box?

I suspect that it has to do with the Zen of Python: "There should be one -- and preferably only one -- obvious way to do it." This would create two obvious ways to access values from dictionaries: obj['key'] and obj.key.

These include possible lack of clarity and confusion in the code. i.e., the following could be confusing to someone else who is going in to maintain your code at a later date, or even to you, if you're not going back into it for awhile. Again, from Zen: "Readability counts!"

>>> KEY = 'foo'
>>> d[KEY] = 1
>>> if d.foo == 1:
...     ...
...

If d is instantiated or KEY is defined or d[KEY] is assigned far away from where d.foo is being used, it can easily lead to confusion about what's being done, since this isn't a commonly-used idiom. I know it would have the potential to confuse me.

As others have noted, you can use any hashable object (not just a string) as a dict key. For example,

>>> d = {(2, 3): True,}
>>> assert d[(2, 3)] is True
>>>
>>> C = type('type_C', (object,), {(2, 3): True})
>>> d = C()
>>> assert d.(2, 3) is True
  File "<stdin>", line 1
  d.(2, 3)
    ^
SyntaxError: invalid syntax
>>> getattr(d, (2, 3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getattr(): attribute name must be string
>>>

is not. This gives you access to the entire range of printable characters or other hashable objects for your dictionary keys, which you do not have when accessing an object attribute. This makes possible such magic as a cached object metaclass, like the recipe from the Python Cookbook (Ch. 9).

I prefer the aesthetics of spam.eggs over spam['eggs'] (I think it looks cleaner), and I really started craving this functionality when I met the namedtuple. But the convenience of being able to do the following trumps it.

>>> KEYS = 'foo bar baz'
>>> VALS = [1, 2, 3]
>>> d = {k: v for k, v in zip(KEYS.split(' '), VALS)}
>>> assert d == {'foo': 1, 'bar': 2, 'baz': 3}
>>>

This is a simple example, but I frequently find myself using dicts in different situations than I'd use obj.key notation (i.e., when I need to read prefs in from an XML file). In other cases, where I'm tempted to instantiate a dynamic class and slap some attributes on it for aesthetic reasons, I continue to use a dict for consistency in order to enhance readability.

I'm sure the OP has long-since resolved this to his satisfaction, but if he still wants this functionality, then I suggest he download one of the packages from pypi that provides it:

dict
  • AttrDict also looks like it's also pretty good, but I'm not as familiar with it and haven't looked through the source in as much detail as I have Bunch.
  • As noted in the comments by Rotareti, Bunch has been deprecated, but there is an active fork called Munch.

However, in order to improve readability of his code I strongly recommend that he not mix his notation styles. If he prefers this notation then he should simply instantiate a dynamic object, add his desired attributes to it, and call it a day:

>>> C = type('type_C', (object,), {})
>>> d = C()
>>> d.foo = 1
>>> d.bar = 2
>>> d.baz = 3
>>> assert d.__dict__ == {'foo': 1, 'bar': 2, 'baz': 3}
>>>

Super cool! Love the type usage

Bunch is deprecated, but there is an active fork of it: github.com/Infinidat/munch

@Rotareti - Thanks for the heads-up! This isn't functionality I use, so I was unaware of that.

python - Accessing dict keys like an attribute? - Stack Overflow

python dictionary syntax
Rectangle 27 17

//get the path of the plist file
guard let plistPath = Bundle.main.path(forResource: "level1", ofType: "plist") else { return }
//load the plist as data in memory
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return }
//use the format of a property list (xml)
var format = PropertyListSerialization.PropertyListFormat.xml
//convert the plist data to a Swift Dictionary
guard let  plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String : AnyObject] else { return }
//access the values in the dictionary 
if let value = plistDict["aKey"] as? String {
  //do something with your value
  print(value)
}
//you can also use the coalesce operator to handle possible nil values
var myValue = plistDict["aKey"] ?? ""

Is there a concise version to this?

ios - Swift - Read plist - Stack Overflow

ios swift
Rectangle 27 4

Regarding retrieving values from the session

userdata() is a method. The way you are accessing it treats it as an array:

$this->session->userdata['user']['name']; // Bad

As the docs describe, you should pass the key of the value you want to retrieve as a parameter to the userdata method:

$user = $this->session->userdata('user');
// Now you can echo $user['name'];
$user = $this->session->user;
// Now you can echo $user['name'];

Check the timestamp fields. They show 3 different times, meaning those are 3 separate events on the site. The first occurs at 1501911275, then 6 seconds later there are another 2 records, and then 139 seconds later the last record. Those represent 3 separate requests to the site - probably you were visiting different pages, or testing and reloading.

As to why there are multiple records, that's because the session ID is periodically regenerated. Exactly how often that happens depends on your configuration see the sess_time_to_update config option. How often they are destroyed also depends on your config (see sess_regenerate_destroy in the same section of the docs) - but normally older session records stick around for a while and are cleaned up later by garbage collection. So while you have only 1 "current" session record, old records can persist for a while.

From the wording of your question I think you want to use the files session driver, and only tried the database driver for testing. If that's correct, there is a problem in your files session configuration which you should fix.

only absolute paths are supported for $config['sess_save_path'].

The comments in config/config.php also say:

Your configuration specifies that session data should be saved in ci_sessions, which is not an absolute path:

$config['sess_save_path'] = 'ci_sessions'; // Bad

I am not sure how will be interpreted, but my guess is the directory won't exist, and the web server will not have permissions to create it. I can't imagine why it works on your live server.

Change the path to an absolute path, and make sure your web server can write to it. Again from the docs

mkdir /<path to your application directory>/sessions/
chmod 0700 /<path to your application directory>/sessions/
chown www-data /<path to your application directory>/sessions/

(change www-data to the user your web server is running as). And then:

$config['sess_save_path'] = '/<path to your application directory>/sessions/';

No, I tried everything what all suggested but nothing was working. Finally, I found the issue, CI 3.1.6 was not supporting PHP 7.1, when I moved back to 5.6, it started saving the session. Thank you so much for your help.

@ShanilSoni I just set up a Docker container with PHP 7.0 and a fresh install of Codeigniter 3.1.6, and sessions work fine. I don't think it is a PHP version problem.

@ShanilSoni If you tried everything suggested here you would have seen that neither of the other 2 answers here actually work, right?

That's why I mentioned in my own answer that maybe this is not the correct explanation but that worked somehow. Yes, none of the answers mentioned here did work. This error I have been trying to resolve past 15 days and for the pages that required sessions to be read, I commented out that code to have that worked otherwise.

php - Sessions not working in localhost but work in live server (Codei...

php codeigniter session
Rectangle 27 1

Use csv.DictWriter, get values from node.attrib dictionary

Your elements named TrdCapRpt have attributes, if you have such node, its attribute node.attrib holds a dictionary with key/value for each attribute.

csv.DictWriter allows writing data taken from dictionary.

First some imports (I always use lxml as it is very fast and provides extra features):

from lxml import etree
import csv

Configure file names and fields to use in each record:

xml_fname = "data.xml"
csv_fname = "data.csv"

fields = [
    "RptID", "TrdTyp", "TrdSubTyp", "ExecID", "TrdDt", "BizDt", "MLegRptTyp",
    "MtchStat" "MsgEvtSrc", "TrdID", "LastQty", "LastPx", "TxnTm", "SettlCcy",
    "SettlDt", "PxSubTyp", "VenueTyp", "VenuTyp", "OfstInst"]
xml = etree.parse(xml_fname)
with open(csv_fname, "w") as f:

    writer = csv.DictWriter(f, fields, delimiter=";", extrasaction="ignore")
    writer.writeheader()
    for node in xml.iter("TrdCaptRpt"):
        writer.writerow(node.attrib)

If you prefer using stdlib xml.etree.ElementTree, you shall manage easily as you do now, because the node.attrib is present there too.

In your comments, you noted, that you want to export attributes from more element names. This is also possible. To do this, I will modify the example to use xpath (which will probably work only with lxml) and add extra column "elm_name" to track, from which element is the record created:

fields = [
    "elm_name",

    "RptID", "TrdTyp", "TrdSubTyp", "ExecID", "TrdDt", "BizDt", "MLegRptTyp",
    "MtchStat" "MsgEvtSrc", "TrdID", "LastQty", "LastPx", "TxnTm", "SettlCcy",
    "SettlDt", "PxSubTyp", "VenueTyp", "VenuTyp", "OfstInst",

    "Typ", "Amt", "Ccy"
]

xml = etree.parse(xml_fname)

with open(csv_fname, "w") as f:

    writer = csv.DictWriter(f, fields, delimiter=";", extrasaction="ignore")
    writer.writeheader()
    for node in xml.xpath("//*[self::TrdCaptRpt or self::PosRpt or self::Amt]"):
        atts = node.attrib
        atts["elm_name"] = node.tag
        writer.writerow(node.attrib)
  • fields got extra "elm_name" field and fields from other elements (feel free to remove those you are not interested at).
  • iterate over elements using xml.xpath. The XPath expression is more complex so I am not sure, if stdlib ElementTree supports that.
  • before writing the record, I add name of the element into atts dictionary to provide name of the element.

Warning: the element Amt is nested inside PosRpt and this tree structure is not possible to support in CSV. The records are written, but do not hold information about where they come from (apart from following the record for parent element).

@Tezirg Added solution for reading from multiple element names.

this is so helpful. One last thing how would I get the header in the csv file ? So i want to have all the tag as headers and then the data

writer.writeheader()
csv.DictWriter

Convert xml to csv in Python - Stack Overflow

python xml csv
Rectangle 27 2417

How can I merge two Python dictionaries in a single expression?

For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.

In Python 3.5 or greater, :

  • In Python 2, (or 3.4 or lower) write a function: def merge_two_dicts(x, y): z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z and z = merge_two_dicts(x, y)

Say you have two dicts and you want to merge them into a new dict without altering the original dicts:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dict's values overwriting those from the first.

>>> z
{'a': 1, 'b': 3, 'c': 4}
z = {**x, **y}

And it is indeed a single expression. It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into What's New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backwards compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z

In both approaches, y will come second and its values will replace x's values, thus 'b' will point to 3 in our final result.

If you are not yet on Python 3.5, or need to write backward-compatible code, and you want this in a single expression, the most performant while correct approach is to put it in a function:

def merge_two_dicts(x, y):
    """Given two dicts, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

and then you have a single expression:

z = merge_two_dicts(x, y)

You can also make a function to merge an undefined number of dicts, from zero to a very large number:

def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

This function will work in Python 2 and 3 for all dicts. e.g. given dicts a to g:

z = merge_dicts(a, b, c, d, e, f, g)

and key value pairs in g will take precedence over dicts a to f, and so on.

Don't use what you see in the formerly accepted answer:

z = dict(x.items() + y.items())

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you're adding two dict_items objects together, not two lists -

>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'

and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.

items()
viewitems()

since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:

>>> c = dict(a.items() | b.items())
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Here's an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:

>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}

Another hack you should not use:

z = dict(x, **y)

This uses the dict constructor, and is very fast and memory efficient (even slightly more-so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.

Here's an example of the usage being remediated in django.

this method fails in Python 3 when keys are not strings.

>>> c = dict(a, **b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dicts for readability purposes, e.g.:

dict(a=1, b=10, c=11)

instead of

{'a': 1, 'b': 10, 'c': 11}

Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-comming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact ** was designed precisely to pass dicts as keywords.

Again, it doesn't work for 3 when keys are non-strings. The implicit calling contract is that namespaces take ordinary dicts, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:

>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}

This inconsistency was bad given other implementations of Python (Pypy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.

My response: merge_two_dicts(x, y) actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dicts have precedence)

You can also chain the dicts manually inside a dict comprehension:

{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

or in python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items())

itertools.chain will chain the iterators over the key-value pairs in the correct order:

import itertools
z = dict(itertools.chain(x.iteritems(), y.iteritems()))

I'm only going to do the performance analysis of the usages known to behave correctly.

import timeit

The following is done on Ubuntu 14.04

>>> min(timeit.repeat(lambda: {**x, **y}))
0.4094954460160807
>>> min(timeit.repeat(lambda: merge_two_dicts(x, y)))
0.7881555100320838
>>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} ))
1.4525277839857154
>>> min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items()))))
2.3143140770262107
>>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items())))
3.2069112799945287

python - How to merge two dictionaries in a single expression? - Stack...

python python-3.x dictionary mapping idioms
Rectangle 27 2404

How can I merge two Python dictionaries in a single expression?

For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.

In Python 3.5 or greater, :

  • In Python 2, (or 3.4 or lower) write a function: def merge_two_dicts(x, y): z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z and z = merge_two_dicts(x, y)

Say you have two dicts and you want to merge them into a new dict without altering the original dicts:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dict's values overwriting those from the first.

>>> z
{'a': 1, 'b': 3, 'c': 4}
z = {**x, **y}

And it is indeed a single expression. It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into What's New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backwards compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z

In both approaches, y will come second and its values will replace x's values, thus 'b' will point to 3 in our final result.

If you are not yet on Python 3.5, or need to write backward-compatible code, and you want this in a single expression, the most performant while correct approach is to put it in a function:

def merge_two_dicts(x, y):
    """Given two dicts, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

and then you have a single expression:

z = merge_two_dicts(x, y)

You can also make a function to merge an undefined number of dicts, from zero to a very large number:

def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

This function will work in Python 2 and 3 for all dicts. e.g. given dicts a to g:

z = merge_dicts(a, b, c, d, e, f, g)

and key value pairs in g will take precedence over dicts a to f, and so on.

Don't use what you see in the formerly accepted answer:

z = dict(x.items() + y.items())

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you're adding two dict_items objects together, not two lists -

>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'

and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.

items()
viewitems()

since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:

>>> c = dict(a.items() | b.items())
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Here's an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:

>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}

Another hack you should not use:

z = dict(x, **y)

This uses the dict constructor, and is very fast and memory efficient (even slightly more-so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.

Here's an example of the usage being remediated in django.

this method fails in Python 3 when keys are not strings.

>>> c = dict(a, **b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dicts for readability purposes, e.g.:

dict(a=1, b=10, c=11)

instead of

{'a': 1, 'b': 10, 'c': 11}

Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-comming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact ** was designed precisely to pass dicts as keywords.

Again, it doesn't work for 3 when keys are non-strings. The implicit calling contract is that namespaces take ordinary dicts, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:

>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}

This inconsistency was bad given other implementations of Python (Pypy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.

My response: merge_two_dicts(x, y) actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dicts have precedence)

You can also chain the dicts manually inside a dict comprehension:

{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

or in python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items())

itertools.chain will chain the iterators over the key-value pairs in the correct order:

import itertools
z = dict(itertools.chain(x.iteritems(), y.iteritems()))

I'm only going to do the performance analysis of the usages known to behave correctly.

import timeit

The following is done on Ubuntu 14.04

>>> min(timeit.repeat(lambda: {**x, **y}))
0.4094954460160807
>>> min(timeit.repeat(lambda: merge_two_dicts(x, y)))
0.7881555100320838
>>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} ))
1.4525277839857154
>>> min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items()))))
2.3143140770262107
>>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items())))
3.2069112799945287

python - How to merge two dictionaries in a single expression? - Stack...

python python-3.x dictionary mapping idioms
Rectangle 27 10

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 10

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 10

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 1525

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
reverse=True
newlist = sorted(l, key=itemgetter('name'), reverse=True)

Using key is not only cleaner but more effecient too.

lambda k: k['name']

itemgetter accepts more than one argument: itemgetter(1,2,3) is a function that return a tuple like obj[1], obj[2], obj[3], so you can use it to do complex sorts.

The fastest way would be to add a newlist.reverse() statement. Otherwise you can define a comparison like cmp=lambda x,y: - cmp(x['name'],y['name']).

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 1519

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
reverse=True
newlist = sorted(l, key=itemgetter('name'), reverse=True)

Using key is not only cleaner but more effecient too.

lambda k: k['name']

itemgetter accepts more than one argument: itemgetter(1,2,3) is a function that return a tuple like obj[1], obj[2], obj[3], so you can use it to do complex sorts.

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 1510

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
reverse=True
newlist = sorted(l, key=itemgetter('name'), reverse=True)

Using key is not only cleaner but more effecient too.

lambda k: k['name']

itemgetter accepts more than one argument: itemgetter(1,2,3) is a function that return a tuple like obj[1], obj[2], obj[3], so you can use it to do complex sorts.

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 1

You need to tell the compiler that you're expecting an array:

if let array = data["key"] as? [Int] {
    let item = array[0]
}

Without that, the compiler only knows that there MAY be an AnyObject in data["key"] (it might also be nil).

swift - Accessing values in a dictionary containing AnyObject - Stack ...

swift
Rectangle 27 22

The other answers work great if the values are strings, however if the values are dictionaries or arrays then this code will handle that.

-(NSString *)serializeParams:(NSDictionary *)params {
    /*

     Convert an NSDictionary to a query string

     */

    NSMutableArray* pairs = [NSMutableArray array];
    for (NSString* key in [params keyEnumerator]) {
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSDictionary class]]) {
            for (NSString *subKey in value) {
                NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                              (CFStringRef)[value objectForKey:subKey],
                                                                                              NULL,
                                                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                              kCFStringEncodingUTF8);
                [pairs addObject:[NSString stringWithFormat:@"%@[%@]=%@", key, subKey, escaped_value]];
            }
        } else if ([value isKindOfClass:[NSArray class]]) {
            for (NSString *subValue in value) {
                NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                              (CFStringRef)subValue,
                                                                                              NULL,
                                                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                              kCFStringEncodingUTF8);
                [pairs addObject:[NSString stringWithFormat:@"%@[]=%@", key, escaped_value]];
            }
        } else {
            NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                          (CFStringRef)[params objectForKey:key],
                                                                                          NULL,
                                                                                          (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                          kCFStringEncodingUTF8);
            [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
            [escaped_value release];
        }
    }
    return [pairs componentsJoinedByString:@"&"];
}
[foo] => bar
[translations] => 
        {
            uno
            dos
            tres
        }

For the final 'else' case, I added a call to description so that it will provide strings for NSNumbers rather than barfing on a call to length: '(CFStringRef)[[params objectForKey:key] description]' Thanks!

CFURLCreateStringByAddingPercentEscapes
stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]

objective c - Creating URL query parameters from NSDictionary objects ...

objective-c nsurl
Rectangle 27 3

As written in the comment by @Lev Levitsky, the dictionary lacks at least one of the keys you are looking for. Instead, you should iterate on the keys of the dictionary, e.g. with

for k in my_dict:

However, you cannot directly alter the dictionary size deleting elements from it while iterating on it at the same time.

So, assuming you want to remove all the items with a values above 50.0

in python 2 only, you can do iterate on they keys returned by .keys() and delete them one by one

for k in d.keys():
    if d[k] < 50.0:
        del d[k]

Alternatively, my suggestion is to use use a dictionary comprehension and generate a new dictionary excluding the unwanted items

new_d = {k:v for k,v in my_dict.items() if v >= 50.0}

then replace the original dictionary and let python's garbage collector do its job

my_dict = new_d

This latter solution works on either version of python.

Note: as pointed out by @Lev Levitsky, you may have a reason for wanting to iterate on a subset of keys instead.

You can't change the dict size during iteration, your first code will raise a RuntimeError.

You can if you just iterate over my_dict.keys() though.

@SuperBiasedMan not in python 3. OK I just noticed now the quesiton is for python 2.7

Removing keys and values from dictionary (Python 2.7) - Stack Overflow

python python-2.7 dictionary key value
Rectangle 27 4

Here is the alternative general solution - it sorts elements of dict by keys and values. The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

def sort_key_func(item):
    """ helper function used to sort list of dicts

    :param item: dict
    :return: sorted list of tuples (k, v)
    """
    pairs = []
    for k, v in item.items():
        pairs.append((k, v))
    return sorted(pairs)
sorted(A, key=sort_key_func)

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 4

Here is the alternative general solution - it sorts elements of dict by keys and values. The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

def sort_key_func(item):
    """ helper function used to sort list of dicts

    :param item: dict
    :return: sorted list of tuples (k, v)
    """
    pairs = []
    for k, v in item.items():
        pairs.append((k, v))
    return sorted(pairs)
sorted(A, key=sort_key_func)

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 4

Here is the alternative general solution - it sorts elements of dict by keys and values. The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

def sort_key_func(item):
    """ helper function used to sort list of dicts

    :param item: dict
    :return: sorted list of tuples (k, v)
    """
    pairs = []
    for k, v in item.items():
        pairs.append((k, v))
    return sorted(pairs)
sorted(A, key=sort_key_func)

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 91

import operator

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age'))

Anyway to combine name and age ? (like in SQL ORDER BY name,age ?)

what is the advantage of itemgetter over lambda ?

@monojohnny: yes, just have the key return a tuple, key=lambda k: (k['name'], k['age']). (or key=itemgetter('name', 'age')). tuple's cmp will compare each element in turn. it's bloody brilliant.

In the documentation (docs.python.org/2/tutorial/datastructures.html) the optional key argument for list.sort() is not described. Any idea where to find that?

list

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures
Rectangle 27 90

import operator

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age'))

Anyway to combine name and age ? (like in SQL ORDER BY name,age ?)

what is the advantage of itemgetter over lambda ?

@monojohnny: yes, just have the key return a tuple, key=lambda k: (k['name'], k['age']). (or key=itemgetter('name', 'age')). tuple's cmp will compare each element in turn. it's bloody brilliant.

In the documentation (docs.python.org/2/tutorial/datastructures.html) the optional key argument for list.sort() is not described. Any idea where to find that?

list

How do I sort a list of dictionaries by values of the dictionary in Py...

python list sorting dictionary data-structures