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
Related
a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}
b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}
Check for the presence of b in a, and the output is a bool value
Tried solutions like this:
for values in b.items():
if values in a.items():
continue
else:
return False
return True
len(set(b.items()) & set(a.items())) == len(b)
The problem is with a value-pair of a key-value whose value-pair is a dictionary. I am looking for a solution to this problem.
maybe this works for you?
a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}
b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}
c = {'a1': 1,'b2': 3}
def issubset(a,b):
for keyb,valueb in b.items():
if keyb in a and a[keyb] == valueb: continue
return False
return True
print( issubset(a,b) )
print( issubset(a,c) )
print( issubset(a,{'a':'2'}) )
output:
True
False
False
it works for your example. However, as you see in the 2nd line, it doesn't do recursive checking, which might be what you want.
Part of the program I am developing has a 2D dict of length n.
Dictionary Example:
test_dict = {
0: {'A': 2, 'B': 1, 'C': 5},
1: {'A': 3, 'B': 1, 'C': 2},
2: {'A': 1, 'B': 1, 'C': 1},
3: {'A': 4, 'B': 2, 'C': 5}
}
All of the dictionaries have the same keys but different values. I need to sum all the values as to equal below.
I have tried to merge the dictionaries using the following:
new_dict = {}
for k, v in test_dict.items():
new_dict.setdefault(k, []).append(v)
I also tried using:
new_dict = {**test_dict[0], **test_dict[1], **test_dict[2], **test_dict[3]}
Unfortuntly I have not had any luck in getting the desired outcome.
Desired Outcome: outcome = {'A': 10, 'B': 5, 'C': 13}
How can I add all the values into a single dictionary?
Solution using pandas
Convert your dict to pandas.DataFrame and then do summation on columns and convert it back to dict.
import pandas as pd
df = pd.DataFrame.from_dict(test_dict, orient='index')
print(df.sum().to_dict())
Output:
{'A': 10, 'B': 5, 'C': 13}
Alternate solution
Use collections.Counter which allows you to add the values of same keys within dict
from collections import Counter
d = Counter()
for _,v in test_dict.items():
d.update(v)
print(d)
I can print variables in python.
for h in jl1["results"]["attributes-list"]["volume-attributes"]:
state = str(h["volume-state-attributes"]["state"])
if aggr in h["volume-id-attributes"]["containing-aggregate-name"]:
if state == "online":
print(h["volume-id-attributes"]["owning-vserver-name"]),
print(' '),
print(h["volume-id-attributes"]["name"]),
print(' '),
print(h["volume-id-attributes"]["containing-aggregate-name"]),
print(' '),
print(h["volume-space-attributes"]["size-used"]
These print function returns for example 100 lines. Now I want to print only top 5 values based on filter of "size-used".
I am trying to take these values in dictionary and filter out top five values for "size-used" but not sure how to take them in dictionary.
Some thing like this
{'vserver': (u'rcdn9-c01-sm-prod',), 'usize': u'389120', 'vname': (u'nprd_root_m01',), 'aggr': (u'aggr1_n01',)}
Any other options like namedtuples is also appreciated.
Thanks
To get a list of dictionaries sorted by a certain key, use sorted. Say I have a list of dictionaries with a and b keys and want to sort them by the value of the b element:
my_dict_list = [{'a': 3, 'b': 1}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4},
{'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 2, 'b': 9}, ]
my_sorted_dict_list = sorted(my_dict_list, key=lambda element: element['b'], reverse=True)
# Reverse is set to True because by default it sorts from smallest to biggest; we want to reverse that
# Limit to five results
biggest_five_dicts = my_sorted_dict_list[:5]
print(biggest_five_dicts) # [{'a': 2, 'b': 9}, {'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4}]
heapq.nlargest is the obvious way to go here:
import heapq
interesting_dicts = ... filter to keep only the dicts you care about (e.g. online dicts) ...
for large in heapq.nlargest(5, interesting_dicts,
key=lambda d: d["volume-space-attributes"]["size-used"]):
print(...)
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'}]
This may be a duplicate but the closest I could find was Comparing 2 lists consisting of dictionaries with unique keys in python which did not work for me.
So I have two lists of dictionaries.
y = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
How do I compare these two lists so my compare results in the intersection of the two lists. I can't convert it to set since it says unhashable type (dict)
Your question and it's title seem at odds with each other.
The intersection of the 2 lists would be the common elements of both list. The question title requests the elements that are not in both lists. Which is it that you want?
For the intersection, it is not very efficient (being O(n^2) in time), but this list comprehension will do it:
>>> a = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
>>> b = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
>>> [d for d in a if d in b]
[{'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
print [x for x in y1 if x in y2] # prints [{'a': 1, 'c': 3, 'b': 2}]
A dict (or list) is not hashable, however, a tuple is. You can convert the list of dicts to a set of tuples. Perform the intersection and then convert back
the code to convert to a set-of-tuples
y_tupleset = set(tuple(sorted(d.items())) for d in y)
the code to convert back the intersected set-of-tuples to a list-of-dicts
y_dictlist = [dict(it) for it in list(y_tupleset)]
Thus, the full code would be:
y0 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
y0_tupleset = set(tuple(sorted(d.items())) for d in y0)
y1_tupleset = set(tuple(sorted(d.items())) for d in y1)
y_inter = y0_tupleset.intersection(y1_tupleset)
y_inter_dictlist = [dict(it) for it in list(y_inter)]
print(y_inter_dictlist)
# prints the following line
[{'a': 1, 'c': 3, 'b': 2}]
edit: d.items() is valid on python3, for python2, it should be replaced with d.iteritems()
Pick your poison:
y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
y3 = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 2, 'c': 6}]
# Returns a list of keys that are in both dictionaries
def intersect_keys(d1, d2):
return [k for k in d1 if k in d2]
# Returns a list of values that are in both dictionaries
def intersect_vals(d1, d2):
return [v for v in d1.itervalues() if v in d2.itervalues()]
# Returns a list of (key,value) pairs that are in both dictionaries
def intersect_pairs(d1, d2):
return [(k,v) for (k,v) in d1.iteritems() if k in d2 and d2[k] == v]
print(intersect_keys(*y1)) # ['a', 'c', 'b']
print(intersect_vals(*y1)) # [3]
print(intersect_pairs(*y1)) # []
print(intersect_keys(*y2)) # ['a', 'c', 'b']
print(intersect_vals(*y2)) # []
print(intersect_pairs(*y2)) # []
print(intersect_keys(*y3)) # ['a', 'c', 'b']
print(intersect_vals(*y3)) # [2]
print(intersect_pairs(*y3)) # [('b', 2)]
Note: the examples compare the two elements of the y* list, which was how I interpreted your question. You could of course use something like:
print(intersect_pairs(y1[0], y2[0]))
To compute the intersection the first dictionary in the y1 and y2 lists.