Python ordereddict to string

Example code for converting an ordered dictionary to JSON using Python

The code contains an ORDEREDDICT followed by data([), which is not immediately followed by RPAREN. However, this is not an issue as per the 3rd rule that allows concatenation of successive data objects. If multiple data objects are present side by side, they can be concatenated. Any object tagged as TEXT is considered as data. As an example, the string «» was converted to: TEXT().

Convert String of OrderedDict to JSON in Python

Perhaps there’s a more feasible approach to address your issue. As far as my understanding goes, ast.literal_eval could be utilized, but the conversion of 2-item tuples to a dictionary must be done manually.

import ast for the_input in [ "OrderedDict()", "OrderedDict([('abc', OrderedDict([('def', 2)]))])", "", "[OrderedDict([('abc', 1)])]", "", "[]", "", "", ]: the_input = the_input.replace("OrderedDict", "") the_output = ast.literal_eval(the_input) print(type(the_output), the_output) 

You can use a parser.

If you have prior knowledge of parsing, then applying it here could be a feasible solution. However, it’s important to note that this is not a straightforward fix.

Python has numerous parsers available, and in this case, let’s consider PLY as an option. Although it may not be the most advanced, it should suffice for your intended purpose.

To parse your text, the initial step is to tokenize it. You can accomplish this task with just a few tokens.

import ply.lex as lex tokens = (LPAREN, RPAREN, ORDEREDDICT, TEXT) t_LPAREN = "(" t_RPAREN = ")" t_ORDEREDDICT = "OrderedDict" t_TEXT = r'(?:(?!(OrderedDict|\(|\))).)+' lexer = lex.lex() 

The parser will categorize the «(» symbol as a «LPAREN» (left-parenthesis), the «)» symbol as a «RPAREN», and recognize the sequence «OrderedDict» as a special element. Any other combination of symbols that does not include parentheses or the sequence «OrderedDict» will be classified as TEXT.

Читайте также:  Python in java app

For instance, the string «» will undergo a conversion process resulting in the output of TEXT(). To verify the functionality, you can carry out a test.

Subsequently, the parsing process can occur.

import ply.yacc as yacc import json def p_ordereddict(p): 'data : ORDEREDDICT LPAREN data RPAREN' p[0] = json.dumps(OrderedDict(json.loads(p[3]))) def p_otherparenthesis(p): 'data : LPAREN data RPAREN' p[0] = p[1]+p[2]+p[3] def p_concat(p): 'data : data data' p[0] = p[1]+p[2] def p_texttodata(p): 'data : TEXT' p[0] = p[1] parser = yacc.yacc() 

This should be read as three rules:

  • Whenever encountering the token «ORDEREDDICT», I am required to search for a left parenthesis immediately following it, followed by a reference to «data», and ultimately ending with a right parenthesis. The entire sequence is then designated as «data», with its corresponding value being the data that was initially contained within the parenthesis but impacted by the «OrderedDict» operator.
  • When a left parenthesis is observed (excluding the previous case), it is necessary to recognize a «data» sequence along with a right parenthesis to complete it. This entire sequence is regarded as data.
  • When multiple data is presented consecutively, I am able to join them together through concatenation.
  • Data is anything that is labeled as TEXT.

To take back our previous example:

The value of the key ‘abc’ is one in an OrderedDict.

The provided statement consists of a dictionary key enclosed within a ordered dictionary and parentheses. The key has a value that is an array containing a tuple with two elements — a string ‘abc’ and an integer 1. The expression is then closed with a final parentheses.

The leftmost position is where the parser begins and searches for a TEXT token. The 4th rule is the only one that considers the presence of TEXT tokens at the beginning, and under this rule, the token is transformed into data.

The information containing a dictionary with a ‘key’ value is passed as an argument to the «data» function. The dictionary is an ordered collection and is enclosed in parentheses. Inside the dictionary, there is a list of text elements which is enclosed in parentheses. The text elements include the string ‘abc’ with an additional integer value of 1. Finally, the dictionary is closed with a closing parentheses.

We currently possess a primary data object, and the rule that dictates the next step is the third one, which necessitates searching for another data object.

Currently, we are searching for data, which is present in an ORDEREDDICT format with the following structure: data().

The 1st rule handles the ORDEREDDICT token, resulting in:

We anticipate receiving information within an ORDEREDDICT data type, enclosed within parentheses. Our current focus is on finding the necessary data within the text enclosed by square brackets, which is located within the parentheses preceding the closing curly brace.

As per the fourth rule, TEXT([) is recognized as information.

We anticipate receiving data in the form of an ORDEREDDICT with a ‘key’. We are currently searching for data within a pair of parentheses and expect to find it in between the TEXT(‘abc’, 1) statements. The overall data should be enclosed in brackets and curly braces.

The fact that RPAREN doesn’t come after data([) is not concerning because the 3rd rule allows for concatenation of successive data objects.

We anticipate the presence of information in a dictionary format with a ‘key’. The structure we expect is an ordered dictionary with an opening parenthesis, followed by data, and then a closing parenthesis. For the next data set, we anticipate a list with an opening parenthesis. Within the list, we expect to find data in the form of text, specifically ‘abc’ with a value of 1. The list should end with a closing parenthesis. Finally, we anticipate a closing parenthesis for the entire data structure.

We anticipate receiving information in the form of an ORDEREDDICT with a ‘key’. Following that, we are looking for data in the form of a list enclosed in parentheses, which should include TEXT(‘abc’, 1), and end with a closing parentheses. Finally, we expect the entire expression to be enclosed in curly braces.

We anticipate receiving information in the form of an ORDEREDDICT with a ‘key’ and a set of data enclosed within parentheses. The data should be enclosed within square brackets and can consist of text, as well as additional sets of data enclosed in parentheses. We are specifically looking for a set of data consisting of the text ‘abc’ and the number 1.

As we have obtained the desired data+RPAREN sequence, we can now conclude by applying the second rule.

An ORDEREDDICT containing a ‘key’ is anticipated in the first portion of the data, followed by data within parentheses. Within the parentheses, an empty list is expected or a tuple containing data (‘abc’, 1). Finally, a closing parenthesis and closing curly brace are anticipated.

At this point, the necessary data has been obtained to implement the third rule.

An ORDEREDDICT is expected to contain data in the ‘key’ attribute. At this point, we are expecting data to be present, followed by an RPAREN. The data should be in the form of a list with a tuple containing a string ‘abc’ and a number 1. Finally, the RPAREN should appear after the data.

The first rule cannot be put into practice at the moment. Therefore, I will proceed by simply listing the steps, assuming that you understand the concept.

The ORDEREDDICT expects data in the ‘key’ parameter. The LPAREN and RPAREN are where we expect data to be present. The data can be in the form of a list of tuples such as data([(‘abc’, 1)]). We are searching for data within the TEXT(). Finally, the RPAREN marks the end of the data.

We are anticipating data to be passed into the function, with a dictionary containing a ‘key’. The data should be in the form of an ordered dictionary, enclosed in parentheses. Inside the ordered dictionary, we anticipate data in the format of key-value pairs, such as (‘abc’, 1). We are looking for this data to be passed as an argument to the function. Text may also be included in the argument, enclosed in curly braces.

We are looking for data in the form of an ORDEREDDICT, enclosed in LPAREN and RPAREN, with the key specified as well. The expected data format is a list of tuples, with each tuple containing a string and an integer value. The final output should be enclosed in TEXT(<>).

We anticipate receiving data in this location, denoted by , followed by the data itself in the form of , and ending with the word TEXT within parentheses.

Presenting the code snippet — data(), TEXT() — where ‘data’ is used to pass the dictionary object with key-value pair, and ‘TEXT’ is a placeholder for the text input.

We are searching for information within TEXT(), containing the key ‘abc’ with a value of 1.

We’re currently searching for data within the parameters of >.

To utilize your parser, all you need to do is invoke its «parse» function. As an illustration:

example = "" parsed = parser.parse(example, lexer=lexer) print(parsed) 

Python | Convert a list of Tuples into Dictionary, Method 1 : Use of setdefault(). Here we have used the dictionary method setdefault() to convert the first parameter to key and the second to the value of the dictionary.setdefault(key, def_value) function searches for a key and displays its value and creates a new key with def_value if the key is not present. …

How can I preserve the order of an OrderedDict when converting it to JSON [duplicate]

As per RFC7159, structured data can be serialized in a text format known as JavaScript Object Notation (JSON. This format is based on JavaScript’s object literals, which were defined in the ECMAScript Programming Language Standard Third Edition [ECMA-262].

An entity is a unordered assemblage that comprises of name/value pairs. The name is a string and the value can be a string, number, boolean, null, object, or array. The entity can be composed of zero or more such pairs.

An ordered collection of values, with no constraint on the number of values, is referred to as an ordered .

To arrange your json, this can be utilized.

@app.route('/') def foobar(): data = OrderedDict([("a",1), ("z",2), ("c",3)]) return json.dumps([data]) 

Enabling the sort_keys parameter (which is False by default) will result in dictionaries being sorted by key in the output. To sort, modify your code as follows:

@app.route('/foobar', methods=['GET']) def foobar() data = [OrderedDict([("a",1), ("z",2), ("c",3)])] return json.dumps(data, sort_keys=True) 

The issue at hand is with OrderedDict , which maintains the order of newly added or modified key/value pairs.

The method in which the dictionary’s key/values are obtained determines the outcome.

Failing is inevitable if you use standard **kwargs.

If the iterable is used to pass or insert the elements, their order will be maintained.

Default keyword arguments

d = OrderedDict(a=1, b=2, c=3) data = [d] print(json.dumps(data)) 

However, when dealing with something that can be iterated over.

d = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) data = [d] print(json.dumps(data)) 

The act of inserting by hand.

d = OrderedDict() d['a'] = 1 d['b'] = 2 d['c'] = 3 data = [d] print(json.dumps(data)) 

And order has been preserved again

Convert python dict to json Code Example, import json appDict = < 'name': 'messenger', 'playstore': True, 'company': 'Facebook', 'price': 100 >app_json = json.dumps(appDict) print(app_json)

Convert JSON to CSV with multiple keys

keys = [] for i in range(0,len(data)): #data is a `dict` for j in data[i]: #  

With the use of dict , obtaining the highest level keys in a dict is made easy.

for key in my_dict: print(key) 

It appears that you are attempting to retrieve the values of data . Another option to consider is utilizing dict , as it can also provide this information.

for value in my_dict.values(): print(value) 

Alternatively, you can acquire both simultaneously.

for key, value in my_dict.items(): print(key, value) 

Python - How can I do to convert OrderedDict to Dict, Then you can use Python's builtin copy.deepcopy () function to perform the conversion. import copy import copyreg from collections import OrderedDict def convert_nested_ordered_dict (x): """ Perform a deep copy of the given object, but convert all internal OrderedDicts to plain dicts along the way. …

Источник

Оцените статью