I have a list of multiple dictionaries (just one of many dictionaries in my list included below) that all have a single value I would like to extract, in the case it would be 'owner'
[
{'Key': 'owner', 'Value': 'connected#work.com'
},
{'Key': 'email_manager', 'Value': 'kort#work.com'
},
{'Key': 'boundary_id', 'Value': '344738728075'
},
}
]
Because owner is the actual value of 'Key' and the value of key 'Value' is the other piece of information needed im having a really hard time getting the desired output, something like:
owner: connected#work.com
I would like to only get that return for all my dictionaries in my list of dictionaries. For context the other dictionaries in my list follow the same formate as what is described.
I think this should work:
keys = []
values = []
for elem in arr:
keys.append(elem['Key'])
values.append(elem['Value'])
new_dict = dict(zip(keys, values))
Try this :
lst_dict = [
{'Key': 'owner', 'Value': 'connected#work.com'},
{'Key': 'email_manager', 'Value': 'kort#work.com'},
{'Key': 'boundary_id', 'Value': '344738728075'}
]
new_lst_dict = [{value['Key'] : value['Value'] for value in lst_dict}]
print(new_lst_dict)
# Output :
# [{'owner': 'connected#work.com','email_manager': 'kort#work.com', 'boundary_id': '344738728075'}]
Related
I have following list of dict:
list_of_dict = [
{'vectorName': 'draw', 'value': 52.06},
{'vectorName': 'c_percentage', 'value': 15.24},
{'vectorName': 'o_temprature', 'value': 1578.0}
]
I have another list of keywords:
list_of_keywords = ['draw', 'o_temprature', 'name', 'c_percentage', 'data']
I want to sort the list of dict based on list of keywords and then get list of values in ordered format :
[512.06, 1578.0, 15.24]
I am trying following peice of code but not working (getting list_of_sorted_dict as None).
list_of_sorted_dict = list_of_dict.sort(key=lambda x: list_of_keywords.index(x["vectorName"]))
Kindly help
Your approach is correct, but the list.sort() is an in-place sorting method, which means that it sorts list_of_dict and returns None. If you want a separate sorted variable, you can do the following.
list_of_sorted_dict = sorted(list_of_dict, key=lambda x: list_of_keywords.index(x["vectorName"]))
you can simply use two fors to achieve that
list_of_dict = [
{'vectorName': 'draw', 'value': 52.06},
{'vectorName': 'c_percentage', 'value': 15.24},
{'vectorName': 'o_temprature', 'value': 1578.0},
]
list_of_keywords = ['draw', 'o_temprature', 'name', 'c_percentage', 'data']
list_of_sorted_dict = []
for key in list_of_keywords:
for item in list_of_dict:
if(item['vectorName'] == key):
list_of_sorted_dict.append(item)
print (list_of_sorted_dict)
result :
[{'vectorName': 'draw', 'value': 52.06}, {'vectorName': 'o_temprature', 'value': 1578.0}, {'vectorName': 'c_percentage', 'value': 15.24}]
I am trying to create a new list from a list of dictionary items.
Below is an example of 1 dictionary item.
{'id': 'bitcoin',
'symbol': 'btc',
'name': 'Bitcoin',
'current_price': 11907.43,
'market_cap': 220817187069,
'market_cap_rank': 1}
I want the list to just be of the id item. So what I am trying to achieve is a list with items {'bitcoin', 'etc', 'etc}
You can use list comprehension:
my_list = [{'id': 'bitcoin', 'symbol': 'btc', ...}, ...]
[d['id'] for d in my_list]
Which translates to : for each dictionary in my_list, extract the 'id' key.
id_list = [d["id"] for d in dictlist ]
This should work for you
list = [ i['id'] for i in list_of_dict]
this should help
Simple and readable code that solves the purpose:
main_list = []
for item in main_dict:
main_list.append(item.get("id", None))
print(main_list)
I have the following list and list of dicts:
data = [dict(position=1, value=150.3),
dict(position=0, value=28.5),
dict(position=2, value=1050.3)]
names = ["CL", "ES", "EUR"]
I would like to map the values of the list into the list of dicts so they match the value stated in the key "position" of the dict - to get the following result:
data = [dict(name="ES", position=1, value=150.3),
dict(name="CL", position=0, value=28.5),
dict(name="EUR", position=2, value=1050.3)]
Is there any "smart" and pythonic way to achieve that?
First of all, please present your question in actual Python form. dict is a type; the way you represent dictionaries in Python is with {}.
Also, you don't have "a dict and list", you have two lists, one of which consists of three dictionaries. So:
data = [
{'position': 1, 'value': 150.3},
{'position': 0, 'value': 28.5},
{'position': 2, 'value': 1050.3}
]
names = ["CL", "ES", "EUR"]
So, given that you do have lists, there is no concern about ordering. A simple loop will give you what you want:
for d in data:
d['name'] = names[d['position']]
This updates data in place:
>>> data
[{'position': 1, 'name': 'ES', 'value': 150.3}, {'position': 0, 'name': 'CL', 'value': 28.5}, {'position': 2, 'name': 'EUR', 'value': 1050.3}]
You can use a list comprehension and dictionary update:
data = [dict(position = 2, value=150.3),
dict(position = 1, value = 28.5),
dict(position=3, value=1050.3)]
names = ['CL', 'ES', 'EUR']
# Sort names according to "position" value of the dictionary
sorted_names = [names[idx] for idx in map(lambda x: x['position'], data)]
# Update modifies inplace
_ = [data[idx].update({'name' : el}) for idx, el in enumerate(sorted_names)]
Which gives the expected output:
data
[{'name': 'ES', 'position': 2, 'value': 150.3},
{'name': 'CL', 'position': 1, 'value': 28.5},
{'name': 'EUR', 'position': 3, 'value': 1050.3}]
You could try:
data = [{"position": 2, "value": 150},
{"position": 1, "value": 200}]
names = ["CL", "ES"]
for item in data:
item["name"] = names[item["pos"] - 1]
Where we go through all the dictionaries in the list, then for each dictionary we set the "name" key to be equal to the value in data at the position described in item["pos"] minus 1.
This of course assumes your data is clean and all items in data correctly map to items in names.
If this is not the case, use a try-except:
for item in data:
try:
item["name"] = names[item["pos"] - 1]
except IndexError:
item["name"] = None
You can also use the update method on the dictionary elements in the list, if you like the keyword-argument convention, as the style of your question suggests.
for item in data:
item.update(name=names[item["position"]])
A one liner implementation using list comprehension.
print [dict(d.items()+[('name',names[d['position']-1])]) for d in data]
I have here a very tricky task here.I want to compare x number of lists in list of lists and that lists contain dictionaries.So i want to compare the dictionaries in these lists based on the 'name' key in the dictionaries if it match it should pass if not it should copy the whole dictionary to the lists that don't have it with editing the 'balance' key vlaue to '0'.
For example let's assume we have list of lists like this :
list_of_lists=[[{'name': u'Profit','balance': 10},{'name': u'Income','balance': 30},{'name': u'NotIncome','balance': 15}],[{'name': u'Profit','balance': 20},{'name': u'Income','balance': 10}]]
So the result should be :
list_of_lists=[[{'name': u'Profit','balance': 10},{'name': u'Income','balance': 30},{'name': u'NotIncome','balance': 15}],[{'name': u'Profit','balance': 20},{'name': u'Income','balance': 10},{'name': u'NotIncome','balance': 0}]]
Here is my code but i can't get it work with 2 lists or more(I don't know the number of lists in the list (maybe 2,3 or 4 etc...) :
for line in lines:
for d1, d2 in zip(line[0], line[1]):
for key, value in d1.items():
if value != d2[key]:
print key, value, d2[key]
You could first create a set containing all the names and then iterate the sublists one by one adding the missing dicts:
import pprint
l = [
[
{'name': u'Profit','balance': 10},
{'name': u'Income','balance': 30},
{'name': u'NotIncome','balance': 15}
],
[
{'name': u'Profit','balance': 20},
{'name': u'Income','balance': 10}
],
[]
]
all_names = {d['name'] for x in l for d in x}
for sub_list in l:
for name in (all_names - {d['name'] for d in sub_list}):
sub_list.append({'name': name, 'balance': 0})
pprint.pprint(l)
Output:
[[{'balance': 10, 'name': u'Profit'},
{'balance': 30, 'name': u'Income'},
{'balance': 15, 'name': u'NotIncome'}],
[{'balance': 20, 'name': u'Profit'},
{'balance': 10, 'name': u'Income'},
{'balance': 0, 'name': u'NotIncome'}],
[{'balance': 0, 'name': u'Profit'},
{'balance': 0, 'name': u'Income'},
{'balance': 0, 'name': u'NotIncome'}]]
That said you should consider converting sublists to dicts where keys are names and values are balances in order to ease the processing.
Sorry if the title is not clear, but here is what I'm trying to achieve.
I have a list of dicts :
l = [{'name': 'inAnalysis'}, {'name': 'inQuest'}, {'name': 'inDevelopment'}]
And a sort of translation table like this :
tr = {'inAnalysis' : 1, 'inDevelopment' : 2, 'inQuest' : 3}
I want to add the key value to l like this :
l = [{'name': 'inAnalysis', 'order' : 1},
{'name': 'inQuest', 'order' : 3},
{'name': 'inDevelopment', 'order' : 2}]
How can I match the value of l with the key of tr and get its value with the key order and add it to l? Any help would be appreciated. I'm using Python 2.6.
You can use list comprehension to dynamically generate the dictionaries like this
print [{"name":dic["name"], "order":tr[dic["name"]]} for dic in l]
Output
[{'name': 'inAnalysis', 'order': 1},
{'name': 'inQuest', 'order': 3},
{'name': 'inDevelopment', 'order': 2}]
Alternatively, you can use the following
for dic in l: dic["order"] = tr[dic["name"]]
this modifies the dictionaries in-place.
If you want to modify the existing dictionaries in place (note that thefoutheye's solution makes new dictionaries which could concievably be a problem if something else in your code is holding a reference to the dictionaries in the list, rather than the list itself) you can do:
for my_dict in l:
my_dict['order'] = tr[my_dict['name']]