I have two lists of dictionaries as below:
old = [{'a': 'aa', 'b': 'bb', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]
new = [{'a': 'aa', 'b': 'boy', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]
In every dictionary in new and old list, the keys are 'a', 'b', 'c'. I need to identify the difference if any in the values. In the example above ideally I want the output to be 'b' and 'c' as the values for those keys have changed. Just identify keys whose values have been modified.
How should I implement this? Thanks!
Try this snippet to see it helps you:
Please ask if there is any questions.
d1 = [{'a': 'aa', 'b': 'bb', 'c': 'cc'},
{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]
d2 = [{'a': 'aa', 'b': 'boy', 'c': 'cc'},
{'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]
for d1, d2 in zip(d1, d2):
#print(d1, d2) # get each dict from d1 and d2
for k in d1: # start to check the key from old (d1)
if k in d2 and d1[k] != d2[k]:
print(k) # b then c
To compare two dictionaries, use something like this:
having dictionaries d1 and d2
differences={key: ( d1[key], d2[key]) for key in d1 if key not in d2 or d1[key]!=d2[key]}
This will compare values from the first dictionary and check if its value is different from the second dictionary. If so, it will yield it.
However, this function will NOT yield keys that exist in one dictionary but not the other.
This is a generator function, so remember to iterate along it or evaluate it with list(...).
old = [{'a': 'aa', 'b': 'bb', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]
new = [{'a': 'aa', 'b': 'boy', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]
def difference(a, b):
for first, second in zip(a, b):
for key, value in first.items():
if key in second:
if value != second[key]:
yield key
print(list(difference(old, new)))
> python .\diff.py
['b', 'c']
Related
Hi new python coder here, let's say I have a list of dictionaries:
data = [{'stat_1': 'name_1', 'stat_2': 10}, {'stat_1': 'name_2', 'stat_2': 12}]
Now I want to add to this list of dictionaries a stat_3 that has the corresponding values for each dictionary item of 100 and 120.
My intended result is:
updated_data = [{'stat_1': 'name_1', 'stat_2': 10, 'stat_3': 100}, {'stat_1': 'name_2', 'stat_2': 12, 'stat_3: 120}]
I know you can append to one dictionary item but how would I go about this with two dictionary items in a list? Is a for loop required? Appreciate the help!
updated_data = data
updated_data[0].update({'stat_3': 100})
updated_data[1].update({'stat_3': 120})
Will sort you, matey.
This should work fine:
data[0]['stat_3'] = 100
data[1]['stat_3'] = 120
if you have a lot of dictionaries in your data list i would do this:
for i in range(len(data)):
data[i]['stat_3'] = value #(whatever value you want)
Here's a one-liner:
data = [{'1': 1, '2': 2}, {'11': 11, '22': 22}]
append = {'C': 'c', 'D': 'd', 'E': 'e'}
[d.update(append) for d in data]
print(data)
As a side-effect, this creates a list full of None as long as len(data). However, no reference to it is saved, so it should be garbage collected immediately.
Output:
[{'1': 1, '2': 2, 'C': 'c', 'D': 'd', 'E': 'e'},
{'11': 11, '22': 22, 'C': 'c', 'D': 'd', 'E': 'e'}]
I have a dictionary:
oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
I want a new dictionary with one of the values in the old dictionary as new key and all the elements as values:
newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
I tried doing this:
newDict['apple'] = oldDict
This does not seem to be working. Please note that I don't have a variable newDict in my script. I just have oldDict and I need to modify the same to make this change in every loop. In the end I will have one dictionary, which will look like this.
oldDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}
You need to duplicate your dictionary so you won't create a circular reference.
>>> newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
>>> newDict['potato'] = dict(newDict)
>>> newDict
{'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}, 'potato': {'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}}}
you need to first create/declare the dictionary before you can added items into it
oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
newDict = {}
newDict['apple'] = oldDict
# {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
# you can 1st create the newDict outside the loop then update it inside the loop
>>> newDict = {}
>>> dict1 = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
>>> dict2 = {'d': 'dog', 'e': 'egg'}
>>> newDict['apple'] = dict1
>>> newDict['dog'] = dict2
>>> newDict
>>> {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}
or you could do as below
newDict = {'apple':oldDict}
I need to write a program that counts the number of values in a dictionary.
For example, say I have this dictionary.
{'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
I should get 6 as a result, because there's 6 values.
When I use this code, I get 4.
def how_many(aDict):
sum = len(aDict.values())
return sum
animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
print(how_many(animals))
I'm very new to Python so please don't do anything to hard.
You need to sum the lengths of each of the elements in aDict.values():
>>> aDict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
>>> sum(len(item) for item in aDict.values())
6
You may use sum on the generator expression to calculate len of each value as:
>>> my_dict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
# returns list of all values v
>>> sum(len(v) for v in my_dict.values())
6
Alternatively, you may also use map with sum to achieve this as:
>>> sum(map(len, my_dict.values()))
6
I have a dictionary of values that gives the number of occurrences of a value in a list. How can I return a new dictionary that divides the former dictionary into separate dictionaries based on the value?
In other words, I want to sort this dictionary:
>>> a = {'A':2, 'B':3, 'C':4, 'D':2, 'E':3}
to this one.
b = {2: {'A', 'D'}, 3: {'B', 'E'}, 4: {'C'}}
How do I approach the problem?
from collections import defaultdict
a = {'A': 2, 'B': 3, 'C': 4, 'D': 2, 'E': 3}
b = defaultdict(set)
for k, v in a.items():
b[v].add(k)
This is what you'll get:
defaultdict(<class 'set'>, {2: {'D', 'A'}, 3: {'B', 'E'}, 4: {'C'}})
You can convert b to a normal dict afterwards with b = dict(b).
if you are a python beginner like me, you probably wanna try this
a = {'A': 2 , 'B': 3 , 'C' : 4 , 'D' : 2, 'E' : 3}
b = {}
for key in a:
lst = []
new_key = a[key]
if new_key not in b:
lst.append(key)
b[new_key] = lst
else:
b[new_key].append(key)
print(b)
It uses the mutable property of python dictionary to achieve the result you want.
How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.
test = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
when I try to make it conditional like this
if any((d['c'] is 8) for d in test):
the value is True or False, But I want the result be an dictionary like
{'a': 'jhon', 'b': 'doe', 'c': 8}
same as if I do
if any((d['a'] is 'crawler') for d in test):
the results is:
{'a': 'crawler', 'b': 'space', 'c': 5}
Thanks in advance
is tests for identity, not for equality which means it compares the memory address not the values those variables are storing. So it is very likely it might return False for same values. You should use == instead to check for equality.
As for your question, you can use filter or list comprehensions over any:
>>> [dct for dct in data if dct["a"] == "crawler"]
>>> filter(lambda dct: dct["a"] == "crawler", data)
The result is a list containing the matched dictionaries. You can get the [0]th element if you think it contains only one item.
Use comprehension:
data = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
print([d for d in data if d["c"] == 8])
# [{'c': 8, 'a': 'jhon', 'b': 'doe'}]