Convert a list to list of dictionaries in Python 3 - python-3.x

I have a dictionary in Python as follows:
result = {"name":"testipgroup",
"ips": ["10.1.1.7","10.1.1.8"],
"team_name": "avengers"}
The output I need is in this format :
result = {"name":"testipgroup",
"ips": [{"name":"IP_10.1.1.7", "value":"10.1.1.7"}],
"team_name": "avengers"}
My implementation involves popping the 'ips' list from the result dict, iterating over the list, doing transformations and then appending the new list of dicts to the result dict as follows:
a = result.pop("ips")
result["ips"] = []
for item in a:
ip_dict = {}
ip_dict.update({"name": "IP_" + str(item), "value": str(item)})
result["ips"].append(ip_dict)
Is there a cleaner way of doing this without popping and creating a new array and doing this directly on the result dict

You can use list comprehension:
result['ips'] = [{'name': 'IP_' + i, 'value': i} for i in result['ips']]
result would become:
{'name': 'testipgroup', 'ips': [{'name': 'IP_10.1.1.7', 'value': '10.1.1.7'}, {'name': 'IP_10.1.1.8', 'value': '10.1.1.8'}], 'team_name': 'avengers'}

It seems like you just want to map over the list and wrap it in a dictionary, with a few tweaks to it? If so, why don't you try using list comprehension?
result['ips'] = [{ 'name':'IP_' + ip, 'value': ip } for ip in result['ips']]

Related

Convert from list of list to dictionary based on the first element of the list

I was learning Python and came upon a problem: To convert a list of list to dictionary based on a certain key.
If the input is: [['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]
The output is: {'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}
The logic being, the first element of the inner array is considered as the key for the new dictionary.
I am currently doing it the dirty way by iterating over the entire list. But, is there a better way to do it?
You'll have to iterate over the list. One way is to use dict.setdefault:
out = {}
for k,v in lst:
out.setdefault(k, set()).add(v)
This is the same as the following conditional loop:
out = {}
for k,v in lst:
if k in out:
out[k].add(v)
else:
out[k] = {v}
Output:
{'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}

Find elements from nested list 1 in nested list 2 and replacing elements

I am trying to modify a nested list_x based on matching elements found in a second nested list_y and replace the element with the item from list_2:
list_x = [['Light_1', 'CC', 'AA'], ['Light_2', 'BB'], ['Light_3', 'DD', 'AA']]
list_y = [['AA', 'ON'], ['BB', 'ON'], ['DD', 'OFF'], ['CC', 'ON'], ['EE', 'ON']]
So the aim is to end up with a list_x looking like:
list_x = [['Light_1', ['CC', 'ON'], ['AA', 'ON']], ['Light_2', ['BB', 'ON']], ['Light_3', ['DD', 'OFF'], ['AA', 'ON']]]
My code so far has only gotten me this:
for n, i in enumerate(list_x):
if i==list_y:
list_x[n]=list_y
list_x
[['Light_1', 'CC', 'AA'], ['Light_2', 'BB'], ['Light_3', 'DD', 'AA']]
Can someone please help find what's missing from my code to get the desired result?
Many thanks
I would first create a dictionary for the second list, so you don't have to search through that list every time you need a match with a key like "AA", "BB", ...etc, but can look it up faster in a dictionary:
dict_y = { key: value for key, value in list_y }
Then, map the first list to your desired output, making use of that dict:
result = [[light, [[key, dict_y[key]] for key in keys]] for light, *keys in list_x]

How to Convert 'dict_items' Object to List

I am loading data from json files using load method and then putting the items in a new python object.
obj_1 = json.load(file)
obj_2 = obj_1.items()
When I run the code in python2, type(obj_2) is list. But when I run in python 3, type(obj_2) is 'dict_items'. Because of that when I run following code:
sorted_items = sorted (obj_2[1][1]['string'])
I'm getting this error in python 3:
TypeError: 'dict_items' object does not support indexing
In python 2 it runs fine. How can I solve this issue in python 3? I have found some related questions about this but the answers doesn't solve my particular case. I have tried to use list(obj_2) but it causes key error.
json file format is something like this:
{
"item_1": {
"item_2": {
"string": 111111,
"string": 222222,
"string": 333333,
................
................
},
},
}
I want to sort the "item_2" contents according to the keys in ascending order.
simply
d = { .... }
l = list(d.items())
making a for loop here is the best option i can think of.
object_list = []
for key, value in obj_2:
entry = [key, value]
object_list.append(entry)
that would store the key and value in a list that is inside another list.
EDIT
Found a better way to do it!
my_dict = {"hello": "there", "how": "are you?"}
my_list = [[x, y] for x, y in my_dict.items()]
# out => [['hello', 'there'], ['how', 'are you?']]
Convert dict items (keys and values) to a list with one line of code. Example:
example_dictionary = {"a": 1, "b": 2, "c": 3}
dict_items_to_list = [*foo.keys(), *foo.values()]
print(dict_items_to_list)
>>> ['a', 'b', 'c', 1, 2, 3]

Using the glom library with Python: Turning a list result into a dictionary with key generated by a Python function

I'm using the Python library glom to extract data from a dictionary that contains lists.
This question is about unterstanding how glom works with user defined functions and how I can move data from lists into dictionaries within glom.
As an example, I'm trying to convert the data into a dictionary directly.
# in the real world, this data has way many more fields
data = {'vessels': [{'aisStatic': {'mmsi': 1, 'name': 'name1'}},
{'aisStatic': {'mmsi': 2, 'name': 'name2'}}],
'timestamp': None}
# this is the glob spec to extract the data
spec = ('vessels',[({'mmsi':'aisStatic.mmsi','name':'aisStatic.name'})])
# an example to generate a new key based on data & position
def keyfunc(i, v):
return f"v{i}-{v['mmsi']}"
result = glom(data, spec)
wanted_result = {keyfunc(i,v): v for i, v in enumerate(result)}
The wanted result looks like this
{'v0-1': {'mmsi': 1, 'name': 'name1'}, 'v1-2': {'mmsi': 2, 'name': 'name2'}}
For the example, I'm using a comprehension outside of glom to get the wanted result, since glom returns a list.
I am looking at a way to get the same results directly via a glom spec.
A working solution is to use Invoke on the enumerate function.
from glom import merge, Invoke
data = {
"vessels": [
{"aisStatic": {"mmsi": 1, "name": "name1"}},
{"aisStatic": {"mmsi": 2, "name": "name2"}},
],
"timestamp": None,
}
spec = (
"vessels",
[{"mmsi": "aisStatic.mmsi", "name": "aisStatic.name"}],
Invoke(enumerate).specs(T),
[lambda x: {f"v{x[0]}-{x[1].get('mmsi')}": x[1]}],
merge,
)
print(glom(data, spec))
which returns the requested result
{'v0-1': {'mmsi': 1, 'name': 'name1'}, 'v1-2': {'mmsi': 2, 'name': 'name2'}}

loop through json objects and add to dictionary with same key and append to list

I want to loop through the json object and add the json values to dictionary and finally append that dictionary to list.
For example:-
lists=[]
dicts={}
for objects in json:
dicts["a"]= objects["abc"]
dicts["b"] = objects["xyz"]
lists.append(dicts)
Input data json:-
{ "json" : [ { 'abc'= 'string1', 'xyz='string2', 'a': 'name'}, { 'abc'= 'john', 'xyz='joe', 'a': 'name'},{ 'abc'= 'b', 'xyz='c', 'a': 'name'} ]}
Expectation for the output is list inside the dictionary like this:-
[{'a': 'string1','b': 'string2'}, {'a': 'john','b': 'joe'}]
How can i achieve this?
Any help much appreciated!
Using dicts you are over-writing with the last value in json instead
Use:
results = []
for objects in json:
results.append({"a": objects["abc"], "b": objects["xyz"]})

Resources