how can I make a dictionary with an exact key order in python?2019 Community Moderator ElectionHow to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory in Python?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of lists?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow to remove a key from a Python dictionary?
Cycles on the torus
When an outsider describes family relationships, which point of view are they using?
cannot log in to the server after changing SSH port
Does the US political system, in principle, allow for a no-party system?
Why restrict private health insurance?
What does the Digital Threat scope actually do?
Is there a math expression equivalent to the conditional ternary operator?
How to copy the rest of lines of a file to another file
Was it really inappropriate to write a pull request for the company I interviewed with?
One circle's diameter is different from others within a series of circles
I reported the illegal activity of my boss to his boss. My boss found out. Now I am being punished. What should I do?
School performs periodic password audits. Is my password compromised?
Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?
Would those living in a "perfect society" not understand satire
Is divide-by-zero a security vulnerability?
Is this Paypal Github SDK reference really a dangerous site?
Do black holes violate the conservation of mass?
What can I do if someone tampers with my SSH public key?
Should we avoid writing fiction about historical events without extensive research?
Is it a Cyclops number? "Nobody" knows!
Traveling to heavily polluted city, what practical measures can I take to minimize impact?
How exactly does an Ethernet collision happen in the cable, since nodes use different circuits for Tx and Rx?
How can I portion out frozen cookie dough?
What should I do when a paper is published similar to my PhD thesis without citation?
how can I make a dictionary with an exact key order in python?
2019 Community Moderator ElectionHow to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory in Python?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of lists?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow to remove a key from a Python dictionary?
I want to make a dictionary with a specific set of keys and a specific set of values. These are the keys I want to use:
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
And these are the values for each key:
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
If I use a set or try to make a dictionary using this:
d = dict(zip(k, v))
Or even this (what I really intend to do):
d = dict(zip(map(lambda x: "ga_%s" % x, k), v))
I get this:
'ga_itemRevenue': 0.0, 'ga_itemQuantity': 1, 'ga_deviceCategory': 'desktop', 'ga_date': datetime.date(2019, 3, 5), 'ga_channelGrouping': 'Tráfico de Búsqueda de Pago - Venta', 'ga_productSku': 60104621, 'ga_productName': '(not set)', 'ga_productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx', 'ga_transactionId': 1551740677701
I know key order is not relevant in python dictionaries (at least, the ones made with dict()
) but I need the keys and their matching values to form the dictionary in the exact same order, which is not alphabetical. Just... the same key order.
I've tried making an ordered dictionary with collections.OrderedDict()
and the order is the one I want except for the fact it gives me a list of tuples. I've also tried to kind of 'convert' the ordered dictionary into a regular one with this:
d = json.loads(json.dumps(x))
But it gives me an error because the datetime
object cannot be serialized (or so it says the error message) and I need it like that (as a datetime
object) as this is going to be written to a database table with the cx_Oracle
package.
I've also read about frozenset()
but seems like I need a previously existing set to 'freeze' it and once I create a set is exactly like trying to make a dictionary. keys are sprayed over the set and I need them in the same order they're declared in the keys array.
How can I achieve this?
#EDIT 1. I forgot to say this is done in Python 2.7.x
#EDIT 2. Here is the code fragment I'm having problems with:
reports = response.get("reports", [])
if len(reports) > 0:
for report in reports:
rows = report.get("data", ).get("rows", [])
if len(rows) > 0:
k = ga_dimensions + ga_metrics
o = []
for row in rows:
o.append(map(lambda x, y: cast_field_type(x, y), row.get("dimensions", []) + row.get("metrics", [])[0]["values"], k))
if len(o) > 0:
# insert all data rows into the table
for v in o:
for i in range(0, len(v)):
if k[i] == "date" and is_date(v[i]):
v[i] = date(*map(int, v[i].split("-")))
elif isinstance(v[i], unicode):
v[i] = v[i].encode("utf-8")
v = dict(zip(map(lambda x: "ga_%s" % x, k), v))
cr.execute(q, v)
# commit all changes
db.commit()
This script fetches data from Google Analytics (using the v4 API), infer the appropiate data types (for database storage with Oracle) from the first row of data, traverse the data rows so specific fields (dates and Unicode strings, basically) get appropiately casted/converted/encoded before being sent to the database and, when done that, commit the changes so the data gets written for real.
I try to do this because the script gives me this error when trying to supply the dictionary per se:
cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER
And this is because the data is being supplied with a key order that is different from the SQL INSERT query being specified.
python python-2.7 dictionary key unordered
add a comment |
I want to make a dictionary with a specific set of keys and a specific set of values. These are the keys I want to use:
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
And these are the values for each key:
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
If I use a set or try to make a dictionary using this:
d = dict(zip(k, v))
Or even this (what I really intend to do):
d = dict(zip(map(lambda x: "ga_%s" % x, k), v))
I get this:
'ga_itemRevenue': 0.0, 'ga_itemQuantity': 1, 'ga_deviceCategory': 'desktop', 'ga_date': datetime.date(2019, 3, 5), 'ga_channelGrouping': 'Tráfico de Búsqueda de Pago - Venta', 'ga_productSku': 60104621, 'ga_productName': '(not set)', 'ga_productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx', 'ga_transactionId': 1551740677701
I know key order is not relevant in python dictionaries (at least, the ones made with dict()
) but I need the keys and their matching values to form the dictionary in the exact same order, which is not alphabetical. Just... the same key order.
I've tried making an ordered dictionary with collections.OrderedDict()
and the order is the one I want except for the fact it gives me a list of tuples. I've also tried to kind of 'convert' the ordered dictionary into a regular one with this:
d = json.loads(json.dumps(x))
But it gives me an error because the datetime
object cannot be serialized (or so it says the error message) and I need it like that (as a datetime
object) as this is going to be written to a database table with the cx_Oracle
package.
I've also read about frozenset()
but seems like I need a previously existing set to 'freeze' it and once I create a set is exactly like trying to make a dictionary. keys are sprayed over the set and I need them in the same order they're declared in the keys array.
How can I achieve this?
#EDIT 1. I forgot to say this is done in Python 2.7.x
#EDIT 2. Here is the code fragment I'm having problems with:
reports = response.get("reports", [])
if len(reports) > 0:
for report in reports:
rows = report.get("data", ).get("rows", [])
if len(rows) > 0:
k = ga_dimensions + ga_metrics
o = []
for row in rows:
o.append(map(lambda x, y: cast_field_type(x, y), row.get("dimensions", []) + row.get("metrics", [])[0]["values"], k))
if len(o) > 0:
# insert all data rows into the table
for v in o:
for i in range(0, len(v)):
if k[i] == "date" and is_date(v[i]):
v[i] = date(*map(int, v[i].split("-")))
elif isinstance(v[i], unicode):
v[i] = v[i].encode("utf-8")
v = dict(zip(map(lambda x: "ga_%s" % x, k), v))
cr.execute(q, v)
# commit all changes
db.commit()
This script fetches data from Google Analytics (using the v4 API), infer the appropiate data types (for database storage with Oracle) from the first row of data, traverse the data rows so specific fields (dates and Unicode strings, basically) get appropiately casted/converted/encoded before being sent to the database and, when done that, commit the changes so the data gets written for real.
I try to do this because the script gives me this error when trying to supply the dictionary per se:
cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER
And this is because the data is being supplied with a key order that is different from the SQL INSERT query being specified.
python python-2.7 dictionary key unordered
1
Prior to Python 3.7, adict
would not preserve any information about the order in which key/value pairs were added. Usecollections.OrderedDict
instead. The issue of preserving adatetime
object across JSON encoding/decoding is an entirely separate problem, though.
– chepner
Mar 6 at 14:04
3
It's only the representation of anOrderedDict
that looks like a list of tuples.
– chepner
Mar 6 at 14:04
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13
add a comment |
I want to make a dictionary with a specific set of keys and a specific set of values. These are the keys I want to use:
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
And these are the values for each key:
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
If I use a set or try to make a dictionary using this:
d = dict(zip(k, v))
Or even this (what I really intend to do):
d = dict(zip(map(lambda x: "ga_%s" % x, k), v))
I get this:
'ga_itemRevenue': 0.0, 'ga_itemQuantity': 1, 'ga_deviceCategory': 'desktop', 'ga_date': datetime.date(2019, 3, 5), 'ga_channelGrouping': 'Tráfico de Búsqueda de Pago - Venta', 'ga_productSku': 60104621, 'ga_productName': '(not set)', 'ga_productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx', 'ga_transactionId': 1551740677701
I know key order is not relevant in python dictionaries (at least, the ones made with dict()
) but I need the keys and their matching values to form the dictionary in the exact same order, which is not alphabetical. Just... the same key order.
I've tried making an ordered dictionary with collections.OrderedDict()
and the order is the one I want except for the fact it gives me a list of tuples. I've also tried to kind of 'convert' the ordered dictionary into a regular one with this:
d = json.loads(json.dumps(x))
But it gives me an error because the datetime
object cannot be serialized (or so it says the error message) and I need it like that (as a datetime
object) as this is going to be written to a database table with the cx_Oracle
package.
I've also read about frozenset()
but seems like I need a previously existing set to 'freeze' it and once I create a set is exactly like trying to make a dictionary. keys are sprayed over the set and I need them in the same order they're declared in the keys array.
How can I achieve this?
#EDIT 1. I forgot to say this is done in Python 2.7.x
#EDIT 2. Here is the code fragment I'm having problems with:
reports = response.get("reports", [])
if len(reports) > 0:
for report in reports:
rows = report.get("data", ).get("rows", [])
if len(rows) > 0:
k = ga_dimensions + ga_metrics
o = []
for row in rows:
o.append(map(lambda x, y: cast_field_type(x, y), row.get("dimensions", []) + row.get("metrics", [])[0]["values"], k))
if len(o) > 0:
# insert all data rows into the table
for v in o:
for i in range(0, len(v)):
if k[i] == "date" and is_date(v[i]):
v[i] = date(*map(int, v[i].split("-")))
elif isinstance(v[i], unicode):
v[i] = v[i].encode("utf-8")
v = dict(zip(map(lambda x: "ga_%s" % x, k), v))
cr.execute(q, v)
# commit all changes
db.commit()
This script fetches data from Google Analytics (using the v4 API), infer the appropiate data types (for database storage with Oracle) from the first row of data, traverse the data rows so specific fields (dates and Unicode strings, basically) get appropiately casted/converted/encoded before being sent to the database and, when done that, commit the changes so the data gets written for real.
I try to do this because the script gives me this error when trying to supply the dictionary per se:
cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER
And this is because the data is being supplied with a key order that is different from the SQL INSERT query being specified.
python python-2.7 dictionary key unordered
I want to make a dictionary with a specific set of keys and a specific set of values. These are the keys I want to use:
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
And these are the values for each key:
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
If I use a set or try to make a dictionary using this:
d = dict(zip(k, v))
Or even this (what I really intend to do):
d = dict(zip(map(lambda x: "ga_%s" % x, k), v))
I get this:
'ga_itemRevenue': 0.0, 'ga_itemQuantity': 1, 'ga_deviceCategory': 'desktop', 'ga_date': datetime.date(2019, 3, 5), 'ga_channelGrouping': 'Tráfico de Búsqueda de Pago - Venta', 'ga_productSku': 60104621, 'ga_productName': '(not set)', 'ga_productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx', 'ga_transactionId': 1551740677701
I know key order is not relevant in python dictionaries (at least, the ones made with dict()
) but I need the keys and their matching values to form the dictionary in the exact same order, which is not alphabetical. Just... the same key order.
I've tried making an ordered dictionary with collections.OrderedDict()
and the order is the one I want except for the fact it gives me a list of tuples. I've also tried to kind of 'convert' the ordered dictionary into a regular one with this:
d = json.loads(json.dumps(x))
But it gives me an error because the datetime
object cannot be serialized (or so it says the error message) and I need it like that (as a datetime
object) as this is going to be written to a database table with the cx_Oracle
package.
I've also read about frozenset()
but seems like I need a previously existing set to 'freeze' it and once I create a set is exactly like trying to make a dictionary. keys are sprayed over the set and I need them in the same order they're declared in the keys array.
How can I achieve this?
#EDIT 1. I forgot to say this is done in Python 2.7.x
#EDIT 2. Here is the code fragment I'm having problems with:
reports = response.get("reports", [])
if len(reports) > 0:
for report in reports:
rows = report.get("data", ).get("rows", [])
if len(rows) > 0:
k = ga_dimensions + ga_metrics
o = []
for row in rows:
o.append(map(lambda x, y: cast_field_type(x, y), row.get("dimensions", []) + row.get("metrics", [])[0]["values"], k))
if len(o) > 0:
# insert all data rows into the table
for v in o:
for i in range(0, len(v)):
if k[i] == "date" and is_date(v[i]):
v[i] = date(*map(int, v[i].split("-")))
elif isinstance(v[i], unicode):
v[i] = v[i].encode("utf-8")
v = dict(zip(map(lambda x: "ga_%s" % x, k), v))
cr.execute(q, v)
# commit all changes
db.commit()
This script fetches data from Google Analytics (using the v4 API), infer the appropiate data types (for database storage with Oracle) from the first row of data, traverse the data rows so specific fields (dates and Unicode strings, basically) get appropiately casted/converted/encoded before being sent to the database and, when done that, commit the changes so the data gets written for real.
I try to do this because the script gives me this error when trying to supply the dictionary per se:
cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER
And this is because the data is being supplied with a key order that is different from the SQL INSERT query being specified.
python python-2.7 dictionary key unordered
python python-2.7 dictionary key unordered
edited Mar 6 at 14:41
Julio María Meca Hansen
asked Mar 6 at 13:59
Julio María Meca HansenJulio María Meca Hansen
803929
803929
1
Prior to Python 3.7, adict
would not preserve any information about the order in which key/value pairs were added. Usecollections.OrderedDict
instead. The issue of preserving adatetime
object across JSON encoding/decoding is an entirely separate problem, though.
– chepner
Mar 6 at 14:04
3
It's only the representation of anOrderedDict
that looks like a list of tuples.
– chepner
Mar 6 at 14:04
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13
add a comment |
1
Prior to Python 3.7, adict
would not preserve any information about the order in which key/value pairs were added. Usecollections.OrderedDict
instead. The issue of preserving adatetime
object across JSON encoding/decoding is an entirely separate problem, though.
– chepner
Mar 6 at 14:04
3
It's only the representation of anOrderedDict
that looks like a list of tuples.
– chepner
Mar 6 at 14:04
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13
1
1
Prior to Python 3.7, a
dict
would not preserve any information about the order in which key/value pairs were added. Use collections.OrderedDict
instead. The issue of preserving a datetime
object across JSON encoding/decoding is an entirely separate problem, though.– chepner
Mar 6 at 14:04
Prior to Python 3.7, a
dict
would not preserve any information about the order in which key/value pairs were added. Use collections.OrderedDict
instead. The issue of preserving a datetime
object across JSON encoding/decoding is an entirely separate problem, though.– chepner
Mar 6 at 14:04
3
3
It's only the representation of an
OrderedDict
that looks like a list of tuples.– chepner
Mar 6 at 14:04
It's only the representation of an
OrderedDict
that looks like a list of tuples.– chepner
Mar 6 at 14:04
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13
add a comment |
3 Answers
3
active
oldest
votes
collections.OrderedDict
seems to do what you want. To illustrate what @chepner mentioned about the representation of OrderedDict
being tuples, I'll show you what I ran:
#encoding: utf-8
from collections import OrderedDict
import datetime
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
d = OrderedDict(zip(k,v))
for i in d:
print(': '.format(i,d[i]))
print('nn')
print(d)
and this was the output:
date: 2019-03-05
deviceCategory: desktop
transactionId: 1551740677701
productSku: 60104621
productName: (not set)
productCategoryHierarchy: sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping: Tráfico de Búsqueda de Pago - Venta
itemRevenue: 0.0
itemQuantity: 1
OrderedDict([('date', datetime.date(2019, 3, 5)), ('deviceCategory', 'desktop'), ('transactionId', 1551740677701), ('productSku', 60104621), ('productName', '(not set)'), ('productCategoryHierarchy', 'sale/apartment/alicante/bajo-vinalopo/elx'), ('channelGrouping', 'Trxc3xa1fico de Bxc3xbasqueda de Pago - Venta'), ('itemRevenue', 0.0), ('itemQuantity', 1)])
So it looks like it's behaving as you were trying to get it to.
add a comment |
The above solution might be what you need, but if you used pandas you'd get an intermediate dataframe which makes manipulating, analyzing, and visualizing data easier (if that's an avenue you wanted). The solution looks something like this:
import datetime
import pandas as pd
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
df = pd.concat([pd.DataFrame(v, k)], axis=1)
# the dataframe
date 2019-03-05
deviceCategory desktop
transactionId 1551740677701
productSku 60104621
productName (not set)
productCategoryHierarchy sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping Tráfico de Búsqueda de Pago - Venta
itemRevenue 0
itemQuantity 1
dict = df.to_dict()
results = dict[0]
results
# the dictionary
'date': datetime.date(2019, 3, 5),
'deviceCategory': 'desktop',
'transactionId': 1551740677701,
'productSku': 60104621,
'productName': '(not set)',
'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
'itemRevenue': 0.0,
'itemQuantity': 1
New contributor
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as withdict(zip(map(lambda x: "ga_%s" % x, k), v))
:S
– Julio María Meca Hansen
Mar 6 at 15:22
add a comment |
Two important things to note:
- make sure you use bind variables (for performance and security).
This will also let you name the variables so the data order shouldn't
matter - when inserting lots of rows it is MUCH more efficient to
useexecuteMany()
as discussed in
https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55024885%2fhow-can-i-make-a-dictionary-with-an-exact-key-order-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
collections.OrderedDict
seems to do what you want. To illustrate what @chepner mentioned about the representation of OrderedDict
being tuples, I'll show you what I ran:
#encoding: utf-8
from collections import OrderedDict
import datetime
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
d = OrderedDict(zip(k,v))
for i in d:
print(': '.format(i,d[i]))
print('nn')
print(d)
and this was the output:
date: 2019-03-05
deviceCategory: desktop
transactionId: 1551740677701
productSku: 60104621
productName: (not set)
productCategoryHierarchy: sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping: Tráfico de Búsqueda de Pago - Venta
itemRevenue: 0.0
itemQuantity: 1
OrderedDict([('date', datetime.date(2019, 3, 5)), ('deviceCategory', 'desktop'), ('transactionId', 1551740677701), ('productSku', 60104621), ('productName', '(not set)'), ('productCategoryHierarchy', 'sale/apartment/alicante/bajo-vinalopo/elx'), ('channelGrouping', 'Trxc3xa1fico de Bxc3xbasqueda de Pago - Venta'), ('itemRevenue', 0.0), ('itemQuantity', 1)])
So it looks like it's behaving as you were trying to get it to.
add a comment |
collections.OrderedDict
seems to do what you want. To illustrate what @chepner mentioned about the representation of OrderedDict
being tuples, I'll show you what I ran:
#encoding: utf-8
from collections import OrderedDict
import datetime
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
d = OrderedDict(zip(k,v))
for i in d:
print(': '.format(i,d[i]))
print('nn')
print(d)
and this was the output:
date: 2019-03-05
deviceCategory: desktop
transactionId: 1551740677701
productSku: 60104621
productName: (not set)
productCategoryHierarchy: sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping: Tráfico de Búsqueda de Pago - Venta
itemRevenue: 0.0
itemQuantity: 1
OrderedDict([('date', datetime.date(2019, 3, 5)), ('deviceCategory', 'desktop'), ('transactionId', 1551740677701), ('productSku', 60104621), ('productName', '(not set)'), ('productCategoryHierarchy', 'sale/apartment/alicante/bajo-vinalopo/elx'), ('channelGrouping', 'Trxc3xa1fico de Bxc3xbasqueda de Pago - Venta'), ('itemRevenue', 0.0), ('itemQuantity', 1)])
So it looks like it's behaving as you were trying to get it to.
add a comment |
collections.OrderedDict
seems to do what you want. To illustrate what @chepner mentioned about the representation of OrderedDict
being tuples, I'll show you what I ran:
#encoding: utf-8
from collections import OrderedDict
import datetime
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
d = OrderedDict(zip(k,v))
for i in d:
print(': '.format(i,d[i]))
print('nn')
print(d)
and this was the output:
date: 2019-03-05
deviceCategory: desktop
transactionId: 1551740677701
productSku: 60104621
productName: (not set)
productCategoryHierarchy: sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping: Tráfico de Búsqueda de Pago - Venta
itemRevenue: 0.0
itemQuantity: 1
OrderedDict([('date', datetime.date(2019, 3, 5)), ('deviceCategory', 'desktop'), ('transactionId', 1551740677701), ('productSku', 60104621), ('productName', '(not set)'), ('productCategoryHierarchy', 'sale/apartment/alicante/bajo-vinalopo/elx'), ('channelGrouping', 'Trxc3xa1fico de Bxc3xbasqueda de Pago - Venta'), ('itemRevenue', 0.0), ('itemQuantity', 1)])
So it looks like it's behaving as you were trying to get it to.
collections.OrderedDict
seems to do what you want. To illustrate what @chepner mentioned about the representation of OrderedDict
being tuples, I'll show you what I ran:
#encoding: utf-8
from collections import OrderedDict
import datetime
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
d = OrderedDict(zip(k,v))
for i in d:
print(': '.format(i,d[i]))
print('nn')
print(d)
and this was the output:
date: 2019-03-05
deviceCategory: desktop
transactionId: 1551740677701
productSku: 60104621
productName: (not set)
productCategoryHierarchy: sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping: Tráfico de Búsqueda de Pago - Venta
itemRevenue: 0.0
itemQuantity: 1
OrderedDict([('date', datetime.date(2019, 3, 5)), ('deviceCategory', 'desktop'), ('transactionId', 1551740677701), ('productSku', 60104621), ('productName', '(not set)'), ('productCategoryHierarchy', 'sale/apartment/alicante/bajo-vinalopo/elx'), ('channelGrouping', 'Trxc3xa1fico de Bxc3xbasqueda de Pago - Venta'), ('itemRevenue', 0.0), ('itemQuantity', 1)])
So it looks like it's behaving as you were trying to get it to.
answered Mar 6 at 14:35
Andrew DeCotiis-MauroAndrew DeCotiis-Mauro
297
297
add a comment |
add a comment |
The above solution might be what you need, but if you used pandas you'd get an intermediate dataframe which makes manipulating, analyzing, and visualizing data easier (if that's an avenue you wanted). The solution looks something like this:
import datetime
import pandas as pd
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
df = pd.concat([pd.DataFrame(v, k)], axis=1)
# the dataframe
date 2019-03-05
deviceCategory desktop
transactionId 1551740677701
productSku 60104621
productName (not set)
productCategoryHierarchy sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping Tráfico de Búsqueda de Pago - Venta
itemRevenue 0
itemQuantity 1
dict = df.to_dict()
results = dict[0]
results
# the dictionary
'date': datetime.date(2019, 3, 5),
'deviceCategory': 'desktop',
'transactionId': 1551740677701,
'productSku': 60104621,
'productName': '(not set)',
'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
'itemRevenue': 0.0,
'itemQuantity': 1
New contributor
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as withdict(zip(map(lambda x: "ga_%s" % x, k), v))
:S
– Julio María Meca Hansen
Mar 6 at 15:22
add a comment |
The above solution might be what you need, but if you used pandas you'd get an intermediate dataframe which makes manipulating, analyzing, and visualizing data easier (if that's an avenue you wanted). The solution looks something like this:
import datetime
import pandas as pd
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
df = pd.concat([pd.DataFrame(v, k)], axis=1)
# the dataframe
date 2019-03-05
deviceCategory desktop
transactionId 1551740677701
productSku 60104621
productName (not set)
productCategoryHierarchy sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping Tráfico de Búsqueda de Pago - Venta
itemRevenue 0
itemQuantity 1
dict = df.to_dict()
results = dict[0]
results
# the dictionary
'date': datetime.date(2019, 3, 5),
'deviceCategory': 'desktop',
'transactionId': 1551740677701,
'productSku': 60104621,
'productName': '(not set)',
'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
'itemRevenue': 0.0,
'itemQuantity': 1
New contributor
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as withdict(zip(map(lambda x: "ga_%s" % x, k), v))
:S
– Julio María Meca Hansen
Mar 6 at 15:22
add a comment |
The above solution might be what you need, but if you used pandas you'd get an intermediate dataframe which makes manipulating, analyzing, and visualizing data easier (if that's an avenue you wanted). The solution looks something like this:
import datetime
import pandas as pd
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
df = pd.concat([pd.DataFrame(v, k)], axis=1)
# the dataframe
date 2019-03-05
deviceCategory desktop
transactionId 1551740677701
productSku 60104621
productName (not set)
productCategoryHierarchy sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping Tráfico de Búsqueda de Pago - Venta
itemRevenue 0
itemQuantity 1
dict = df.to_dict()
results = dict[0]
results
# the dictionary
'date': datetime.date(2019, 3, 5),
'deviceCategory': 'desktop',
'transactionId': 1551740677701,
'productSku': 60104621,
'productName': '(not set)',
'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
'itemRevenue': 0.0,
'itemQuantity': 1
New contributor
The above solution might be what you need, but if you used pandas you'd get an intermediate dataframe which makes manipulating, analyzing, and visualizing data easier (if that's an avenue you wanted). The solution looks something like this:
import datetime
import pandas as pd
k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']
v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]
df = pd.concat([pd.DataFrame(v, k)], axis=1)
# the dataframe
date 2019-03-05
deviceCategory desktop
transactionId 1551740677701
productSku 60104621
productName (not set)
productCategoryHierarchy sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping Tráfico de Búsqueda de Pago - Venta
itemRevenue 0
itemQuantity 1
dict = df.to_dict()
results = dict[0]
results
# the dictionary
'date': datetime.date(2019, 3, 5),
'deviceCategory': 'desktop',
'transactionId': 1551740677701,
'productSku': 60104621,
'productName': '(not set)',
'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
'itemRevenue': 0.0,
'itemQuantity': 1
New contributor
New contributor
answered Mar 6 at 14:48
SamSam
917
917
New contributor
New contributor
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as withdict(zip(map(lambda x: "ga_%s" % x, k), v))
:S
– Julio María Meca Hansen
Mar 6 at 15:22
add a comment |
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as withdict(zip(map(lambda x: "ga_%s" % x, k), v))
:S
– Julio María Meca Hansen
Mar 6 at 15:22
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
using Pandas is an option for me so... I'm going to try it. Thank you very much for your suggestion :)
– Julio María Meca Hansen
Mar 6 at 14:50
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
No problem! Hope it solves your issue. :)
– Sam
Mar 6 at 14:55
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as with
dict(zip(map(lambda x: "ga_%s" % x, k), v))
:S– Julio María Meca Hansen
Mar 6 at 15:22
Demons! I must be doing something really nasty with the data or it's the pre-processing of each column what's tampering with the dictionary because... I get exactly the same result as with
dict(zip(map(lambda x: "ga_%s" % x, k), v))
:S– Julio María Meca Hansen
Mar 6 at 15:22
add a comment |
Two important things to note:
- make sure you use bind variables (for performance and security).
This will also let you name the variables so the data order shouldn't
matter - when inserting lots of rows it is MUCH more efficient to
useexecuteMany()
as discussed in
https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle
add a comment |
Two important things to note:
- make sure you use bind variables (for performance and security).
This will also let you name the variables so the data order shouldn't
matter - when inserting lots of rows it is MUCH more efficient to
useexecuteMany()
as discussed in
https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle
add a comment |
Two important things to note:
- make sure you use bind variables (for performance and security).
This will also let you name the variables so the data order shouldn't
matter - when inserting lots of rows it is MUCH more efficient to
useexecuteMany()
as discussed in
https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle
Two important things to note:
- make sure you use bind variables (for performance and security).
This will also let you name the variables so the data order shouldn't
matter - when inserting lots of rows it is MUCH more efficient to
useexecuteMany()
as discussed in
https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle
answered Mar 6 at 21:35
Christopher JonesChristopher Jones
2,1141715
2,1141715
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55024885%2fhow-can-i-make-a-dictionary-with-an-exact-key-order-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Prior to Python 3.7, a
dict
would not preserve any information about the order in which key/value pairs were added. Usecollections.OrderedDict
instead. The issue of preserving adatetime
object across JSON encoding/decoding is an entirely separate problem, though.– chepner
Mar 6 at 14:04
3
It's only the representation of an
OrderedDict
that looks like a list of tuples.– chepner
Mar 6 at 14:04
OrderedDict behaves exactly like a dict , what are you trying to do with it that makes it not behave like one?
– AntiMatterDynamite
Mar 6 at 14:13