Handling a dictionary that has keys that are unicode strings - python

I have a dictionary that each key is unicode and I'm using the following code to insert JSON file into a dictionary.
def readDictFromFile(filename):
my_file = Path(filename)
if my_file.is_file():
return json.load(codecs.open(filename,encoding='utf-8'))
return {}
But when I try to check if a string is in the dictionary, it does not work:
if title in dict:
continue
The reason is that the dict contains keys that look like: u'\u05d5. I say that I need to use repr (link) but is there a way to do it with the same syntax without looping for each key in the dict?

Related

How to Identify an dictionary inside an dictionary

I have a dictionary like this:
test = {'user_id':125, 'company':'XXXX', 'payload': {"tranx": "456b62448367","payload": {"snr": "25%","Soil": 45,"humidity": 85}}}
The requirement is :
the payload inside a dictionary(test), is dynamic sometimes the payload will come and sometimes it won't, and the payload name is temporary, may after some time it will become "abc" or anything.
In this case,
I want to Identify the "test" is a nested dict or not.
If it is nested dict I want to know the "key" of the nested dictionary, How can I solve this.
iterate and check
for key, value in outer_dict.items():
if isinstance(value, dict):
print(key)

Parse single qouted dictionary key and value in Python

I have a Python dictionary
original_dict={'body': '{"infra":["dev4","elk"],{"type":"file_integrity"}'}
I want to be able to parse original_dict keys and values as a normal dictionary which I am not able to do now because 'body' key has a a dictionary casted as string and therefore I am not refer to any of it's keys. So I should be able to say:
infra=original_dict['body]['infra']
Can anyone help me out with this.
First of all, you are missing a curly brace in the original_dict.
Here is an example of converting a string into a dictionary.
import json
original_dict={'body':'{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = json.loads(original_dict['body'])
infra=original_dict['body']['infra']
print(infra)
Output : ['dev4', 'elk']
You can use ast too:)
import ast
original_dict = {'body': '{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = ast.literal_eval(original_dict['body'])

How to access a dictionary key inside a string

I have an API that expects to receive the data in a string format. The data looks like this:
test = """{"API_name":"getScenario","token":"1112223333","clientId":"1","clientEmail":"yup#nope#gmail.com", "more": "hello"}"""
I am used to accessing the dictionary keys rather easily test[token] but in this case it is all encased in a multi-line string.
How is this supposed to be accessed?
Parse the string and then find access by key
import json
data = json.loads(test)
data['API_name']

Having trouble parsing some JSON in python

I'm trying to parse some JSON data from https://mtgjson.com/json/AllCards.json but I'm not sure how to deal with the way its structured. Here's a snippet of my code:
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for card in cards:
print(card)
I was expecting "card" to be a dictionary that I could then use to access attributes, for example "card['name']". However all "card" is in this case is a string containing the the key value so I cant use it to access any of the nested attributes. If I print "cards" though, it outputs the entire JSON document including all of the nested attributes.
I also tried accessing them using cards[0] but this gave me a key error.
I'm obviously missing something here but I cant figure out what.
Iterating a dictionary will by default iterate its keys.
If you walso want the values, you should iterate dict.items() instead:
import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for key, value in cards.items():
print(key, value)
value will contain the sub-dict.
It's the same as
import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for key in cards:
print(key, cards[key])
If you don't care about the key, you can iterate the values directly:
import json
cards = json.loads(open("AllCards.json", encoding="utf8").read())
for card in cards.values():
print(card)

Using A Python List or String in Dictionary Lookup?

Use Case
I am making a factory type script in Python that consumes XML and based on that XML, returns information from a specific factory. I have created a file that I call FactoryMap.json that stores the mapping between the location an item can be found in XML and the appropriate factory.
Issue
The JSON in my mapping file looks like:
{
"path": "['project']['builders']['hudson.tasks.Shell']",
"class": "bin.classes.factories.step.ShellStep"
}
path is where the element can be found in the xml once its converted to a dict.
class is the corresponding path to the factory that can consume that elements information.
In order to do anything with this, I need to descend into the dictionaries structure, which would look like this if I didn't have to draw this information from a file(note the key reference = 'path' from my json'):
configDict={my xml config dict}
for k,v in configDict['project']['builders']['hudson.tasks.Shell'].iteritems():
#call the appropriate factory
The issue is that if I look up the path value as a string or a list, I can not use it in 'iteritems'():
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
for k,v in configDict[path].iteritems():
#call the appropriate factory
This returns a key error stating that I can't use a string as the key value. How can I used a variable as the key for that python dictionary?
You could use eval:
eval( "configDict"+path )
You can use the eval() function to evaluate your path into an actual dict object vs a string. Something like this is what I'm referring to:
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
d = eval("configDict%s" % path)
for k,v in d.iteritems():
#call the appropriate factory

Categories

Resources