Why json.keys() get keys in different order [duplicate] - python

This question already has answers here:
How to convert json string to dictionary and save order in keys? [duplicate]
(1 answer)
Can I get JSON to load into an OrderedDict?
(6 answers)
Closed 9 years ago.
Hi i have the following code in python:
import json
jsonpost = json.loads('{"Player": {"_id": "3","firstName":"kim","surname":"jones"},"newTable": {"_id": "4","SurName": "abcd"}}')
for key in jsonpost.keys():
for innerkey in jsonpost[key]:
print innerkey
my question is why when i print out inner key the order of the keys for jsonpost['Player'] is the following:
_id , surname, firstName

Python dictionaries are implemented internally with a hash table. This means that key order is not preserved. Is this an issue?

keys in a dictionary are never in the same order, if you want them consistently in the same order for your code, you could do
sorted(jsonpost.keys())

Either JavaScript's JSON nor Python's dict have the concept of ordering. You can use collections.OrderedDict in Python to get away with it, but JavaScript does not have such an alternative.

Python dictionaries are inherently unordered, so when you print them out, the keys can be out of order.
If order is important, you can use an OrderedDict:
import collections
jsonpost = collections.OrderedDict(sorted(jsonpost.items()))
Or you can change to for loop to:
for key in sorted(jsonpost.keys()):
for innerkey in jsonpost[key]:
print innerkey

Dictionary ordering is specified as being unspecified, you could sort(whatever.keys()) or you could use and ordered dictionary, i.e. collections.OrderedDict if you are running python 2.7 or later.

Related

Appending item to a list within dictionary without checking if the key exists [duplicate]

This question already has answers here:
fill a dictionary without using try except
(4 answers)
Closed 4 years ago.
Currently, in order to do what I'm describing, I have a code like this:
if key in dict:
dict[key].append(item)
else:
dict[key] = [item]
Is there any way I can append to list within dictionary without doing the explicit check?
Can this be done using another data structure?
What I need to do is to track all the items that have some parameter equal.
d = {}
d.setdefault(1, []).append('item')
in python .get used to retrieve key and optional argument to get if value not exist, however it will give you only initial value.
whereas in .setdefault you will get a value for corresponding key or else it will initialise key with default value passed as another argument

Python data structure and their C++ equivalent

I am looking for python equivalent to these data structure in C++
map<string,set<string>>
sorted by key
the value to be a set
and
map<key,val>
sorted by key
After reading this: https://docs.python.org/2/library/collections.html#collections.OrderedDict
I still didn't find anything suitable.
In python do you have 4 data structures: lists, tuples, sets and dicts.
You can create your own structure combining them:
First:
data = {'my_set':set()}
Second:
data = {'key': 'value'}
And you can sort this data structures using the collections module.
How can I sort a dictionary by key?
There is no perfect mapping between c++ and python; python is dynamically typed.
map<string,set<string>> is equivalent to (using OrderedDict to preserve the order of the keys, otherwise, dict suffice.):
OrderedDict(), where the keys are strings, and the values are sets in which you insert strings
from collections import OrderedDict
a = OrderedDict()
a['my_key'] = set()
a['my_key'].add('my_string')
note. The OrderedDict will not be ordered "by key", but by insertion
order of the keys (thanks to #timgeb in the comments)

SQLalchemy return tuples when querying all() [duplicate]

This question already has answers here:
Query for list of attribute instead of tuples in SQLAlchemy
(4 answers)
SQL Alchemy ORM returning a single column, how to avoid common post processing
(7 answers)
Closed 5 years ago.
I'm trying to get a list of integers, for this query:
session.query(C.ex_id).filter(c.foo==foo).all()
I get a list of tuples instead of list of integers. I don't want to iterate over the list I get, I want to get it form the query itself.
What can I do?
This may not be exactly what you want, but one work around is:
some_list = map(lambda (x,):x, session.query(C.ex_id).filter(c.foo==foo).all())

pymongo find on list instead of db [duplicate]

This question already has answers here:
Testing a filter on a document on client-side
(2 answers)
Closed 6 years ago.
Is there a way to use the pymongo find method on a list (or iterable) of dictionaries instead on performing the search on the database?
I have a list of dictionaries and I'd like to filter them using queries like in pymongo.
Is there any library that can do that?
you don't need an external library to accomplish that simple task. If i understand correctly you just need to filter a list of dictionaries based on some value.
def find(dict_list, key, value_list):
return [dict for dict in dict_list if dict[key] in value_list]
You can then pass a list of dictionaries a key to match and values of that key that you want to search.

How to maintain order of key/value pairs in dictionary of python? [duplicate]

This question already has answers here:
How do you retrieve items from a dictionary in the order that they're inserted?
(11 answers)
Closed 3 years ago.
I am creating a module in which a dictionary is used. This dictionary contains some key/value pairs, whose order must be preserved when using in other modules. But whenever I iterate over dictionary and print the keys, the keys are not in the order in which they key/value pairs are inserted.
So my question is how should I preserve the order of key/value pair in a dictionary?
Any help will be highly appreciated...
Thanx in advance...
We know that regular Python dictionaries iterate over pairs in an arbitrary order, hence they do not preserve the insertion order of pairs.
Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the same interface like the general dictionaries but it traverse through keys and values in an ordered manner depending on when a key was first inserted.
Eg:
from collections import OrderedDict
d = OrderDict([('Company-id':1),('Company-Name':'Intellipaat')])
d.items() # displays the output as: [('Company-id':1),('Company-Name':'Intellipaat')]

Categories