This question already has answers here:
List of dicts to/from dict of lists
(14 answers)
Closed 4 years ago.
so given a list of dictionaries:
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'},
{'a': '1', 'b': '8', 'c': '1', 'd': '2'},
{'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
and a list of keys in the dictionary for example [ 'a', 'b']
I am trying to make a list of dictionaries for both 'a' and 'b' for their respective values i.e the final product will resemble
new_dict = ['a':['4', '1', '7'], 'b':['5', '8', '4']]
any help will be appreciated
Using collections
Demo:
import collections
d = collections.defaultdict(list)
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'}, {'a': '1', 'b': '8', 'c': '1', 'd': '2'}, {'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
for i in my_dict:
for k,v in i.items():
d[k].append(v)
print( d )
Output:
defaultdict(<type 'list'>, {'a': ['4', '1', '7'], 'c': ['1', '1', '1'], 'b': ['5', '8', '4'], 'd': ['3', '2', '5']})
Related
container = {'15/09/2021': {'a': '5', 'b': '7', 'c': '9', 'd': 'missing', 'e': '18'}, '16/09/2021': {'a': '6', 'b': '7', 'c': '9', 'd': '10', 'e': '12'}, '17/09/2021': {'a': '7', 'b': '8', 'c': '10', 'd': '11', 'e': 'missing'}, '18/09/2021': {'a': '9', 'b': '12', 'c': '15', 'd': 'missing', 'e': 'missing'}}
with open('output.json', 'w') as outfile:
json.dump(container, outfile, indent=4)
The result I'm getting :
This is the desired result :
I think both pictures are the same JSON, only thing is different it is the indentation.
Suppose, there is a dictionary like
my_dict = {'A': {'5', '7', '9', '3'},
'B': {'4', '8','3'},
'C': {'5', '3', '2', '9'},
'D': {'1','6', '8','3'},
'E': {'4','3','5'}}
Now the output should be like {A,C} because they have most number of common values.
dct = {'A': {'5', '7', '9', '3'}, 'B': {'4', '8','3'}, 'C': {'5', '3', '2', '9'}, 'D': {'1','6', '8','3'}, 'E': {'4','3','5'}}
ans = [None, None]
mx = 0
for i in dct:
for j in dct:
if i != j and len(dct[i].intersection(dct[j])) > mx:
ans = [i, j]
mx = len(dct[i].intersection(dct[j]))
As there are sets contained, to find number of common elements, we have intersection method.
>>> ans
['A', 'C']
Although, its worth noting that this code would always produce a pair. If you want more number of elements, the number of loops is going to increase accordingly.
This question already has answers here:
Combining lists of dictionaries based on list index
(2 answers)
Closed 3 years ago.
I having an issue of finding a way to merge these three lists into one in Python3.
list1 = [{'a': '1'}, {'a': '2'}, {'a': '3'}]
list2 = [{'b': '4'}, {'b': '5'}, {'b': '6'}]
list3 = [{'c': '7'}, {'c': '8'}, {'c': '9'}]
What I would like to do is getting a new list such as:
list4 = [{'a': '1', 'b': '4', 'c': '7'}, {'a': '2', 'b': '5', 'c': '8'}, {'a': '3', 'b': '6', 'c': '9'}]
Is there any Pythonic way to do this operation?
Use zip in a combined list- and dict comprehension:
>>> list1 = [{'a': '1'}, {'a': '2'}, {'a': '3'}]
>>> list2 = [{'b': '4'}, {'b': '5'}, {'b': '6'}]
>>> list3 = [{'c': '7'}, {'c': '8'}, {'c': '9'}]
>>> [{k: d[k] for d in ds for k in d} for ds in zip(list1, list2, list3)]
[{'a': '1', 'b': '4', 'c': '7'},
{'a': '2', 'b': '5', 'c': '8'},
{'a': '3', 'b': '6', 'c': '9'}]
Also works if the dicts contain more than one value. If the dicts in one "column" contain the same keys, the values in the later lists will overwrite the former.
I'm trying to loop through a list of dictionaries and search for a specific key. If the value of that key matches a specific value, another list of dictionaries is provided. I would like to append the original list of dictionaries with the new dictionaries.
def test():
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
for item in info:
if "1" in item['a']:
info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
for dict in info2:
info.append(dict)
I was hoping my above attempt would result in the original info list being as follows:
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}, {'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
however I just end up with TypeErrors:
TypeError: string indices must be integers.
Thanks in advance for any assistance
Some issues in your code
You are trying to modify the info list you are iterating on, instead you should iterate on the copy of info via for item in info[:]:
You can change item['a'] to item.get('a') to make sure getting item doesn't thwo an exception if the key is not present, and you can change in to equality
You can add the dictionaries from info2 list to info list by extend the list using list.extend
Then your updated code will be
def test():
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
#Iterate on copy of info
for item in info[:]:
#If value of a equals 1
if item.get('a') == '1':
#Extend the original list
info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
info.extend(info2)
return info
print(test())
And the output will be
[
{'a': '1', 'b': '2'},
{'a': '3', 'b': '4'},
{'c': '1', 'd': '2'},
{'c': '3', 'd': '4'}
]
For example i have dict python
dict = {'a': '1', 'b': '2', 'c': '3'}
and array
arr = ['4', '5', '6']
I want add sequential value array to dict
dict1 = {'a': '4', 'b': '5', 'c': '6'}
Please suggest a specific solution.
>>> d = {'a': '1', 'b': '2', 'c': '3'}
>>> arr = ['4', '5', '6']
>>> dict(zip(sorted(d), arr))
{'a': '4', 'c': '6', 'b': '5'}
You can use zip:
>>> import string
>>> arr = ['4', '5', '6']
>>> # dict(zip(sorted(original_dict), arr))
>>> dict(zip(string.ascii_lowercase, arr))
{'b': '5', 'c': '6', 'a': '4'}
BTW, don't name a varialbe dict. It will shadows builtin type/function dict.
Not sure what you are trying to do, but the below code snippet does what you intend in your question.
import os
dict = {'a': '1', 'b': '2', 'c': '3'}
arr = ['4', '5', '6']
dict1 = {}
dictAsList = dict.items()
i = 0
for key in sorted(dict):
try:
dict1[key] = arr[i]
except:
pass
i = i+1
print dict1
Python dictionary doesn't have order. So I don't get what sequential means in dictionary.
If you just want to set all value to another value you can do like this.
d = {'a': '1', 'b': '2', 'c': '3'}
arr = ['4', '5', '6']
print dict(zip(d.keys(), arr))
#{'a': '4', 'c': '5', 'b': '6'}
If you want to set value as same order you can do like this.(You need change your data structure)
from collections import OrderedDict
d = OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])
arr = ['4', '5', '6']
print dict(zip(d.keys(), arr))
#{'a': '4', 'c': '6', 'b': '5'}