Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
As I understand, a dict has every key unique; if you put two identical key in a dict the first key will be overwritten by the second like this example
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'age': 40
}
print(my_dict)
The result will be
{'name': 'John', 'age': 40, 'city': 'New York'}
How can I manage to do so the second will be overwritten by the first like this example?
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'age': 40
}
print(my_dict)
I want the result to be
{'name': 'John', 'age': 30, 'city': 'New York'}
I tried functions but the dict already does that by default. So no point on doing a function.
Related
I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a key in the 1st dictionary, 2nd new value to a key in the 2nd dictionary, etc.
My data looks something like this:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
And I want to transform the list of dictionaries using the list of new jobs according to my description into this:
dict_list = [{'person':'Tom', 'job':'lecturer'},
{'person':'John', 'job':'cook'},
{'person':'Mary', 'job':'driver'}]
As I have a very long list of dictionaries I would like to define a function that would do this automatically but I am struggling how to do it with for loops and zip(), any suggestions?
I tried the for loop below. I guess the following code could work if it was possible to index the dictionaries like this dictionary['job'][i] Unfortunately dictionaries don't work like this as far as I know.
def update_dic_list():
for dictionary in dict_list:
for i in range(len(new_jobs)):
dictionary['job'] = new_jobs[i]
print(dict_list)
The output the code above gave me was this:
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'teacher'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'driver'}]
If your new_jobs list has the right job for each corresponding entry in the dict list, you could use zip:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
for d, j in zip(dict_list, new_jobs):
d['job'] = j
print(dict_list)
prints
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]
With your loop, for each dictionary, you're going through the new jobs and updating that same dictionary over and over with each of the jobs until the last one. So by the end of it, they'll all be drivers. Because that's the last one.
You can do
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
def update_dic_list():
for job, _dict in zip(new_jobs, dict_list):
_dict['job'] = job
or
def update_dict_list():
for i, job in enumerate(new_jobs):
dict_list[i]['job'] = job
You only need to remove the inner loop because you are changing dictionary key job more than one time for each of item of outer loop:
def update_dic_list():
i = 0
for dictionary in dict_list:
dictionary['job'] = new_jobs[i]
i += 1
print(dict_list)
Or alternatively you could use enumerate:
def update_dic_list():
for i, dictionary in enumerate(dict_list):
dictionary['job'] = new_jobs[i]
print(dict_list)
Output:
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]
I am trying to update the values of the dictionary as the values provided by another list, but the update is happening to all of the previous values as well.
Here is my code snippet:
dict = {'name' : 'shubham', 'age': 23}
listDict = [dict]*5
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
Output is coming :
[{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23}]
It should be coming :
[{'name': 'sh', 'age': 23},
{'name': 'shu', 'age': 23},
{'name': 'shub', 'age': 23},
{'name': 'shubh', 'age': 23},
{'name': 'shubha', 'age': 23}]
When you do the [dict]*5 operation, what you have afterwards is a list of 5 references to the same dictionary object in memory, thus when you edit one you are actually editing all of them. For more explanation of this, look up the difference between Mutable and Immutable objects in python (this occurs because dictionaries are mutable).
To accomplish what you want, you need to explicitly make copies of the initial dict.
listDict = [dict.copy() for i in range(5)]
This should create the result you expect.
(also friendly tip: your should avoid naming your first dictionary dict: that shadows the dict() function and is confusing to read!)
If you create a list of dictionaries like this: [dict]*5 the dictionaries will be linked to each other.
So I suggest you to do the multiplication this way:
dict = {'name' : 'shubham', 'age': 23}
listDict = [ dict.copy() for i in range(5) ]
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
Hope I helped!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I have the following list:
[{'infoType': {'name': 'PERSON_NAME'}, 'count': '71'},
{'infoType': {'name': 'LOCATION'}, 'count': '2'},
]
I would like to transform this list in order to get
[{'name': 'PERSON_NAME',
'count': '71'},
{'name': 'LOCATION',
'count': '2'},
]
Thanks for the help
You can use something like this:
lst = [{'infoType': {'name': 'PERSON_NAME'}, 'count': '71'}, {'infoType': {'name': 'LOCATION'}, 'count': '2'}]
output = []
for d in lst:
newDict = {}
newDict['name'] = d['infoType']['name']
newDict['count'] = d['count']
output.append(newDict)
print(output)
Output:
[{'name': 'PERSON_NAME', 'count': '71'},
{'name': 'LOCATION', 'count': '2'}]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
The current problem consists of the conversion of a dictionary to a list. I am unable to split the specific value of key and value pair into my desired results.
I have a dictionary that looks like this:
dict = [ {name:aa,age:12, id:121}, {name:bb,age:13, id:122},{name:cc,age:11, id:121}, {name:dd,age:15, id:122} ]
It has certain pairs of key and values and the 'ID' key is the most important of them.the ID value is repeated and so I am looking for lists of that value such that it would looks like this:
121 = [
{name:aa,age:12},
{name:cc,age:11}
]
122 = [
{name:bb,age:13},
{name:dd,age:15}
]
I think this should work fine, just looping through the list of sub-dictionaries.
start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]
converted_dict = {}
for subdict in start_dict:
if subdict['id'] not in converted_dict:
converted_dict[subdict['id']] = [{k:v for k,v in subdict.items() if k != 'id'}]
else:
converted_dict[subdict['id']].append({k:v for k,v in subdict.items() if k != 'id'})
print(converted_dict)
{121: [{'name': 'aa', 'age': 12}, {'name': 'cc', 'age': 11}],
122: [{'name': 'bb', 'age': 13}, {'name': 'dd', 'age': 15}]}
from collections import defaultdict
start_dict = [
{'name': 'aa', 'age': 12, 'id': 121},
{'name': 'bb', 'age': 13, 'id': 122},
{'name': 'cc', 'age': 11, 'id': 121},
{'name': 'dd', 'age': 15, 'id': 122},
]
new_dict = defaultdict(list)
for entry in start_dict:
new_dict[entry["id"]].append(dict(name=entry["name"], age=entry["age"]))
print(dict(new_dict))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm struggling to get the result from the following code:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
My expected result is to group them by highest score (to show highest score per user), how do I do that?
Expected Result:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
Here's a way to do it with an ordered dictionary, without pandas:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
ord_dict = collections.OrderedDict()
for i in sorted(list_result, key=lambda x: x["score"]):
ord_dict[i["name"]] = i["score"]
print([{"name":k, "score":v} for k,v in ord_dict.items()])
The output is:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
You can use pandas.DataFrame and its groupby() method like this:
>>> import pandas as pd
>>> df = pd.DataFrame(list_result)
>>> df.groupby('name').score.max().reset_index().to_dict(orient='records')
[{'name': 'James', 'score': 8}, {'name': 'John', 'score': 6}]
import collections
import math
list_result = [
{'name':'John', 'score': 5},
{'name':'John', 'score': 6},
{'name':'James', 'score': 7},
{'name':'James', 'score': 8}
]
max_score_by_user = collections.defaultdict(lambda: -math.inf)
for result in list_result:
name, score = result['name'], result['score']
max_score_by_user[name] = max(max_score_by_user[name], score)
print(*max_score_by_user.items(), sep='\n')
Which prints:
('John', 6)
('James', 8)
You can try:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
output_dict = {}
for result in list_result:
if result["name"] in output_dict:
if result["score"] > output_dict[result["name"]]:
output_dict[result["name"]] = result["score"]
else:
output_dict[result["name"]] = result["score"]
output_list = []
for output_key, output_val in output_dict.items():
output_list.append({"name": output_key, "score": output_val})
print(output_list)
Output:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Copy
Sample Output:
Maximum Value: 5874
Minimum Value: 500