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?










0















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.










share|improve this question



















  • 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






  • 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















0















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.










share|improve this question



















  • 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






  • 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













0












0








0








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.










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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, 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





    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












  • 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






  • 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







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












3 Answers
3






active

oldest

votes


















1














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.






share|improve this answer






























    1














    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





    share|improve this answer








    New contributor




    Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




















    • 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 with dict(zip(map(lambda x: "ga_%s" % x, k), v)) :S

      – Julio María Meca Hansen
      Mar 6 at 15:22


















    0














    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
      use executeMany() as discussed in
      https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle





    share|improve this answer






















      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
      );



      );













      draft saved

      draft discarded


















      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









      1














      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.






      share|improve this answer



























        1














        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.






        share|improve this answer

























          1












          1








          1







          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.






          share|improve this answer













          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 6 at 14:35









          Andrew DeCotiis-MauroAndrew DeCotiis-Mauro

          297




          297























              1














              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





              share|improve this answer








              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















              • 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 with dict(zip(map(lambda x: "ga_%s" % x, k), v)) :S

                – Julio María Meca Hansen
                Mar 6 at 15:22















              1














              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





              share|improve this answer








              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















              • 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 with dict(zip(map(lambda x: "ga_%s" % x, k), v)) :S

                – Julio María Meca Hansen
                Mar 6 at 15:22













              1












              1








              1







              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





              share|improve this answer








              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.










              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






              share|improve this answer








              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.









              share|improve this answer



              share|improve this answer






              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.









              answered Mar 6 at 14:48









              SamSam

              917




              917




              New contributor




              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





              New contributor





              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.












              • 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 with dict(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











              • 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
















              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











              0














              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
                use executeMany() as discussed in
                https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle





              share|improve this answer



























                0














                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
                  use executeMany() as discussed in
                  https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle





                share|improve this answer

























                  0












                  0








                  0







                  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
                    use executeMany() as discussed in
                    https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle





                  share|improve this answer













                  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
                    use executeMany() as discussed in
                    https://blogs.oracle.com/opal/efficient-and-scalable-batch-statement-execution-in-python-cx_oracle






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 6 at 21:35









                  Christopher JonesChristopher Jones

                  2,1141715




                  2,1141715



























                      draft saved

                      draft discarded
















































                      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.




                      draft saved


                      draft discarded














                      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





















































                      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







                      Popular posts from this blog

                      1928 у кіно

                      Захаров Федір Захарович

                      Ель Греко