Dictionary to JSON for loop - python

I've tried just about everything to convert a dictionary that looks like this in Python:
d = {'name': 'Jack', 'age': 26}
I know you're able to access values like this:
d['name']
> Jack
I would like to do this in a for loop though:
for obj in d:
print(obj['name'])
Any ideas how? I've tried both json.loads and json.dumps on obj but keep getting errors like: string indices must be integers. How can I can access specific keys and get their values like the example above?

You need to access .values() of your main dict
d = {'person-1': {'name':'Jack', 'age':'26'}, 'person-2': {'name':'Idk', 'age':'23'}}
for obj in d.values():
print(obj['name'])
Jack
Idk
And .items() to get the outer key with
for key, obj in d.items():
print(key, obj['name'])
person-1 Jack
person-2 Idk

Related

how to delete and add multiple items without iterating a dictionary in python 3.7x?

I wonder if a existing dictionary instance can add and/or delete multiple items without using iterations.
I mean something like this.
supposition:(it actually doesn't work)
D = {"key1":"value1", "key2":"value2", "key3":"value3"}
tags = ["key1","key2"]
D.pop(tags)
print(D)
{"key3":"value3"}
Thank you in advance.
If so, you could iterate a list instead of iterate the full dict:
D = {"key1":"value1", "key2":"value2", "key3":"value3"}
for i in ["key1", "key2"]:
D.pop(i)
print(D)
If you don't actually need to avoid iteration, but rather just want to do the transformation of the dictionary in an expression, rather than a statement, you could use a dictionary comprehension to create a new dictionary containing only the keys (and the associated values) that don't match your list of things to remove:
D = {key: value for key, value in D.items() if key not in tags}
Unfortunately, this doesn't modify D in place, so if you need to change the value referenced through some other variable this won't help you (and you'd need to do an explicit loop). Note that if you don't care about the values being removed, you probably should use del D[key] instead of D.pop(key).
If all you're wanting to do is show the dictionary where key from list is not present, why not just create a new dic:
D = {"key1":"value1", "key2":"value2", "key3":"value3"}
tags=["key1", "key2"]
dict = {key:value for key, value in D.items() if key not in tags}
print(dict)

KeyError with dict

I have the following
a = {'afaf178a0a3e4f91812d36a3c3289dbd': {'profile_id': 'afaf178a0a3e4f91812d36a3c3289dbd', 'cute_name': 'Watermelon'}, 'cd1800ef65ea4ac7a65effed5ed420d0': {'profile_id': 'cd1800ef65ea4ac7a65effed5ed420d0', 'cute_name': 'Peach'}, 'b673d818a57f4cdeb549c0cbe152ed51': {'profile_id': 'b673d818a57f4cdeb549c0cbe152ed51', 'cute_name': 'Papaya'}}
When trying to access it using a[0] I get a KeyError. Why is this?
Your dictionary has keys:
>>> a.keys()
['b673d818a57f4cdeb549c0cbe152ed51', 'afaf178a0a3e4f91812d36a3c3289dbd', 'cd1800ef65ea4ac7a65effed5ed420d0']
You should use one of those to access the values. Otherwise you may iterate over keys with:
for k in a.keys() :
pass # put something here
Or you may iterate over the values:
for v in a.values() :
pass # put something here
Or you may iterate over both:
for k,v in a.items() :
pass # put something here
Python raises a KeyError whenever a dict() object is requested and the key is not in the dictionary.
Using the dictionary in your post as an example:
>>> a.keys()
dict_keys(['afaf178a0a3e4f91812d36a3c3289dbd', 'cd1800ef65ea4ac7a65effed5ed420d0', 'b673d818a57f4cdeb549c0cbe152ed51'])
0 is not in the dictionary you provided, hence the KeyError.

how to purge the nested json element to uppermost key in python without using 'key' of upper element

So basically, I have the following json:
{'firstName': {'value': 'xyz'}}
Now I want to convert this into:
{'firstName':'xyz'}
without using the keyname 'firstname' i.e. is there a way to purge the nested dictionary?
Yes, you could, for datum with that type of structure
{'x': {'y':'z'}}
I would do this:
def removeInnerDict(to_parse_dict):
parsed_dict = dict()
for key, inner_dict in to_parse_dict.items():
inner_value = list(inner_dict.values())[0]
parsed_dict.update({key: inner_value})
return parsed_dict
The function removeInnerDict caters for arbitrary size of dictionary, as long as you stick to the specified format

Sorting and merge values of a python dict

I got a problem with a dict I want to sort in python 3.5.
It looks like :
d = {'automate': <Routing.Route.Route object at 0x2b7f84835c18>,
'index': <.Routing.Route.Route object at 0x2b7f8486e5c0>,
'index_1': <Routing.Route.Route object at 0x2b7f8483d400>,
'index_2': <Routing.Route.Route object at 0x2b7f84835f98>,
'second': <Routing.Route.Route object at 0x2b7f8483d470>,
'test_route_parameters': <Routing.Route.Route object at 0x2b7f8486e588>}
Where Route class has name, package_name attributes.
I want to print this dict like:
>> Package_name1:
automate
index
index_1
Package_name2:
second
index_2
Package_name3:
test_route_parameters
How can I sort my dict by package_name and print it to match the above output?
Have a good day and thank you.
This will do the trick:
{v.package_name:[k for k in d if d[k].package_name==v.package_name] for v in d.values()}
This should work. Loop through the dictionary and check if the package name in value is present in the sorted_dict. If not, add a list as value and package_name as key and then just append the keys to each package_name. Runs in O(n).
sorted_dict = {}
for key in d:
if d[key] not in sorted_dict:
sorted_dict[d[key].package_name] = []
sorted_dict[d[key].package_name].append(d[key])

Iterating through (JSON?) map in Python

I have a datastructure like that:
sample_map= {'key1': {'internal_key1': ['value1']},
'key2': {'internal_key2': ['value2']},
}
I would like to iterate throgh on every line key1 and key2. I would like to get the value of 'internal_key1' and 'value_1'variables.
I tried this way:
for keys in sample_map.keys():
for value in sample_map[keys]:
#get internal_keys and values
How should I do this? Someone maybe could tell me about this data structure and the using?
for item in sample_map.values():
for k, v in item.items():
print k, v
How about the following:
for k,v in sample_map.iteritems():
print k
for k1,v1 in v.iteritems():
print k1,v1[0]
This will print the following:
key2
internal_key2 value2
key1
internal_key1 value1
This is called a dictionary (type dict). It does resemble the JSON structure, although JSON is a format in which a string is built to represent a specific structure of data, and dict is a structure of data (that can be converted to a string in JSON format).
Anyway, this line - for value in sample_map[keys]: is invalid. To get the value linked to a key, you just have to do value = sample_map[keys]. In this example, dicts will be assigned to val. Those will be the inner dicts ({'internal_key1': ['value1']} and so on).
So to access the inner keys, call .keys() of value:
for keys in sample_map.keys():
value = sample_map[keys]:
for internal_key in value.keys():
internal_value = value[internal_key]
Also, when using a for loop, there's no need for dict.keys(), it will be used automatically, so your code could look like:
for keys in sample_map:
value = sample_map[keys]:
for internal_key in value:
internal_value = value[internal_key]

Categories