adding values to objects in dictionary - python-3.x

I want to add the following to each object in a dictionary.
My dictionary looks like this:
{'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}
For each object I want to add the following value:
{'type':'object'}
So the final outcome should look something like this:
{'Niveau1Obj1': {'type': 'object'}, 'Niveau2Obj1': {'type': 'object'}, 'Niveau3Obj1': {'type': 'object'}}
My code doesn't result in the desired outcome. The code is:
objects = {'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}
for key, obj in objects.items():
objects[key].setdefault(key, {}).update({'type':'object'})
It only adds the {'type':'object'} only to the last part of the dictionary.
What am I doing wrong?

Try a recursion:
dct = {"Niveau1Obj1": {"Niveau2Obj1": {"Niveau3Obj1": {}}}}
def get_keys(d):
if isinstance(d, dict):
for k in d:
yield k
yield from get_keys(d[k])
out = {k: {"type": "object"} for k in get_keys(dct)}
print(out)
Prints:
{
"Niveau1Obj1": {"type": "object"},
"Niveau2Obj1": {"type": "object"},
"Niveau3Obj1": {"type": "object"},
}

Related

Getting error when doing re-mapping dict keys to another dict keys in python

below is my code:
mapping_dict = {"NET_D":
[
("name", "tiN"),
("d_id", "id"),
("m_ip", "ti_ip"),
("model", "cmbM"),
("dc", "cmbL"),
("vendor", "cmbV"),
("cab", "cmbC")
]
}
obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}
def process_results(item_list, mapping):
results = []
for i in item_list:
item = {}
for m in mapping:
try:
item[m[0]] = i[m[1]]
except KeyError:
item[m[0]] = ""
results.append(item)
return results, len(results)
process_results(obj, mapping_dict["NET_D"])
desired/wanted output:
{"m_ip": "1.1.1.1", "model": "model-a", "name": "device-123", "vendor": "Systems", "cab": "406", "dc": "sc", "d_id": "199"}
error i am getting:
process_results
item[m[0]] = i[m[1]]
TypeError: string indices must be integers
can anyone suggest the right way to achieve desired/wanted output
i am still new to python, apologies for the mistakes/errors or if my code sounds like silly/dumb ;-) to you
You could do this, although technically your mapping_dict is a list of tuples and not a nested dict.
mapping_dict = {"NET_D":
[
("name", "tiN"),
("d_id", "id"),
("m_ip", "ti_ip"),
("model", "cmbM"),
("dc", "cmbL"),
("vendor", "cmbV"),
("cab", "cmbC")
]
}
obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}
def process_results(item_list, mapping):
return {i[0]:v for k,v in item_list.items() for i in mapping if k == i[1]}
which will give
{'m_ip': '1.1.1.1', 'model': 'model-a', 'name': 'device-123', 'vendor': 'Systems', 'cab': 'sc', 'd_id': '199'}```
This is called dict comprehension and creates a new dictionary.
It is basically doing the equivalent of
def process_results(item_list, mapping):
res = {}
for k,v in item_list.items():
for i in mapping:
if k == i[1]:
res[i[0]] = v
return res
Iterating for each value of the obj dict, then iterate through the mapping list of tuples and if the value is the same as index[1] of the tuple then create a new key:value in the new dict.

Python3 - recursively replace all keys with periods in a nested dictionary

I am trying to clean up a nested dictionary before inserting it into Mongo. Some of the keys in the dict have periods in them so I need to replace them with underscores. Based on other posts I have seen I have come up with this (not working) code sample:
def get_recursively(search_dict):
new_dict = {}
for key, value in search_dict.items():
if '.' in key or ' ' in key:
new_dict[key.replace('.', '_').replace(' ', '_').lower()] = value
elif isinstance(value, dict):
results = get_recursively(value)
for key2, value2 in results.items():
new_dict[key] = dict(key2, value2)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item)
for key3, value3 in more_results.items():
new_dict[key] = dict(key3, value3)
else:
new_dict[key] = value
return new_dict
I am trying to make a new dictionary because when I tried to modify the existing dictionary I got an error about the dictionary changing during execution.
The code that is not valid (at least) is:
dict(key2, value2)
That is not valid syntax but hopefully shows my thought process at least.
Any help much appreciated.
If I understood right, is this want you meant?
def change_chars(string, chars, new_char):
new_string = string
for char in chars:
new_string = new_string.replace(char, new_char)
return new_string
def recursively_change_keys(obj, chars, new_char):
if isinstance(obj, list):
return [
recursively_change_keys(o, chars, new_char)
for o in obj
]
elif isinstance(obj, dict):
return {
change_chars(key, chars, new_char): recursively_change_keys(value, chars, new_char)
for key, value in obj.items()
}
return obj
So you just have to call it like recursively_change(search_dict, [ ".", " " ], "_")
Try:
import json
d = {
"some.key": [
{
"key.1": {"a": 1},
"key.2": 2,
"key.3": {"key.4": [3, 4, 5], "key.5": 6},
}
]
}
def transform(d):
if isinstance(d, dict):
return {k.replace(".", "_"): transform(v) for k, v in d.items()}
elif isinstance(d, list):
return [transform(v) for v in d]
else:
return d
# pretty print the dictionary:
print(json.dumps(transform(d), indent=4))
Prints:
{
"some_key": [
{
"key_1": {
"a": 1
},
"key_2": 2,
"key_3": {
"key_4": [
3,
4,
5
],
"key_5": 6
}
}
]
}

Dictionary using distinct characters as values

I need to make a dictionary using the string list as keys and their distinct characters as values.
I have tried some functions and ended up with the following code but I cannot seem to add the string key into it
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield dict (i=len(set(i)))
print (list(distinct_characters(value))
I would like to get
{ "check" : 4, "look" : 3, "try" : 3, "pop" : 2}
but I keep getting
{ "i" : 4, "i" : 3, "i" : 3, "i" : 2}
Well, string is itself an iterable, so don't call list on dicts instead call dict on list of tuples like below.
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield (i, len(set(i)))
print(dict(distinct_characters(value)))
Output:
{'check': 4, 'look': 3, 'try': 3, 'pop': 2}
Consider the simple dictionary comprehension:
value = ["check", "look", "try", "pop"]
result = {key: len(set(key)) for key in value}
print(result)
Thanks for the replies
I needed to answer it as a function for a class exercise so I ended up using this code:
value=["check", "look", "try", "pop"]
print(value)
def distinct_characters(x):
for i in x:
yield (i, len(set(i)))
print(dict(distinct_characters(value)))
Thanks again

How to get the value of the first key of each dictionary in a list using LOOP?

Sample code:
dict1 = {"firstname":"Anna", "lastname":"Lupe", "ID":12000789}
dict2 = {"firstname":"Max", "lastname":"Mustermann", "ID":12345}
list_of_dict = [dict1, dict2]
print(list_of_dict)
Output:
[{'firstname': 'Anna', 'lastname': 'Lupe', 'ID': 12000789}, {'firstname': 'Max', 'lastname': 'Mustermann', 'ID': 12345}]
How can I get(print) all first names using a LOOP? Say, something like:
for el in list_of_dict:
print el[0]
However dictionary does not support indexing...
Get dict keys using dict.keys(), then convert it to a list and get first one.
dict1 = {"firstname": "Anna", "lastname": "Lupe", "ID": 12000789}
dict2 = {"firstname": "Max", "lastname": "Mustermann", "ID": 12345}
list_of_dict = [dict1, dict2]
print(list_of_dict)
for el in list_of_dict:
first_key = list(el.keys())[0]
print(el[first_key])

how to convert dict value use lambda map in python

the format data like this, To explain, I have this dict:
{
'41': [
'1029136700',
'1028348931'
],
'42': ['12234454']
...
}
then i want to convert the format like this used lambda and map:
[
{
'key':'41','value':'1029136700'
},
{
'key':'41','value': '1028348931'
},
{
'key':'42', 'value': '12234454'
}
...
]
Can you give me a clue on how to achieve this in python?
Here is a clue on how to get what you want - you have to iterate over the initial dictionary:
for key, list_of_vals in initial_dictionary.items():
for val in list_of_vals:
# now you have pairs
# for example, key = '41', val = '1029136700'
# use them as you need
Just couple more steps and you get exactly what you want.
However, if you want to do this with map() and lambda it would not be that easy. You have to replace every for loop (there 2 of them) with map() containing lambda. map() returns generator so you have to iterate over it to get actual result, for example, list(map(...)). Here is complete code how you can get what you want:
result = list()
set(map(lambda item: result.extend(list(
map(lambda val: {'key': item[0], 'value': val},
item[1]))),
initial_dictionary.items()))
print(result)
Output:
[{'key': '41', 'value': '1029136700'}, {'key': '41', 'value': '1028348931'}, {'key': '42', 'value': '12234454'}]
This implementation is significantly more difficult to read and understand.

Resources