I know that len(dict) would give the number of keys but what i want is this
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,1], [1,7,9], [6,2,3]],
'c': [['a'], [4,5]],
}
The number i want in this case is 7, 7 being the number of elements in 'a' + number of elements in 'b' + number of elements in 'c'
Given a dictionary
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,1], [1,7,9], [6,2,3]],
'c': [['a'], [4,5]],
}
You can get the sum of the lengths of each value using
sum(map(len, mydict.values()))
Please correct your example, it is not valid python dict.
I assumed that against every key you have list of lists.
dict = {
'a': [[2,4],[5,6]],
'b': [[1,1],[1,7,9],[6,2,3]],
'c': [[3],[4,5]]
}
Your answer:
print sum (len(element) for element in dict.values());
Your code is not a valid python dictionary.
This is a valid dictionary:
dict = {
'a': ([2,4],[5,6]),
'b': ([1,1],[1,7,9],[6,2,3]),
'c': ([a],[4,5])
}
Use tuples to group multi-value items with fixed size (they have better performance than lists).
The answer to the question, using the correct dictionary, is
sum([len(e) for e in dict.values()])
Related
{'A': [5.0, 6.20], 'B': [1.92, 3.35], 'C': [3.21, 7.0], 'D': [2.18, 9.90]}
I will then manipulate the numbers according to the key matches.
So for example, A, I'd take those numbers and plug-into an equation accordingly.
x/100 * y/100 = 5.0/100 * 6.20/100
Note that this is part of a function that returns values.
You can use a dict comprehension to do this for each key.
{k:(x/100) * (y/100) for k,(x,y) in d.items()}
{'A': 0.0031000000000000003,
'B': 0.0006432,
'C': 0.002247,
'D': 0.0021582000000000003}
Accessing a single key's value in a dictionary is as simple as just d['A'] or d.get('A')
Read more about dict comprehensions here.
EDIT: Thanks for the cleaner code suggestion #Olvin Roght
After accessing the dictionary values with their key, in this example 'A' then access the list values with their index. Index [0] of the list holds 'val1' for example. Which you can then assign to a variable and do your math.
dict
Code
dic = {'A':['val1', 'val2']}
x = dic['A'][0]
y = dic['A'][1]
print(x, y)
Result
val1 val2
I want to do something like this:
my_dict = {
('a'|'b'|'c') : 1
}
Clearly, this doesn't work but I was wondering if there are ways around it that are the same or more efficient than writing each out:
my_dict = {
'a' : 1,
'b' : 1,
'c' : 1
}
Any ideas?
You can create a dictionary with multiple keys all mapping to the same value using dict.fromkeys.
The first argument is a sequence of keys; the second argument is the value.
>>> dict.fromkeys('abc', 1)
{'a': 1, 'b': 1, 'c': 1}
'abc' works as a sequence of keys because in this case all your keys are strings of one character. More generally you can use a tuple or a list:
>>> dict.fromkeys(['a','b','c'], 1)
{'a': 1, 'b': 1, 'c': 1}
(N.B. creating a dict this way might cause problems if your value was mutable, since all the keys would reference the same value object.)
Create a dictionary with 3 keys, all with the value 1:
x = ('a', 'b', 'c')
y = 1
thisdict = dict.fromkeys(x, y)
print(thisdict)
I have this dictionary containing lists as they're values for keys.
d = {'n': ['a', 'b', 'x'], 'a': [1, 2, 3], 'p': ['123', '321', '456']}
And I want to convert into a list of dictionary as such
[{'n': 'a', 'a': 1, 'p': '123'}, {'n': 'b', 'a': 2, 'p':
'321'}, {'n': 'x', 'a': 3, 'p': '456'}]
My current solution is,
the_kv = d.items()
f = {}
c = {}
e = {}
f_c_e = []
for i, j in the_kv:
f[i] = j[0]
c[i] = j[1]
e[i] = j[2]
f_c_e.append(f)
f_c_e.append(c)
f_c_e.append(e)
print(f_c_e)
But I was wondering if there is a more efficient way rather than creating separate dicts and then appending them to a list.
Using zip:
[dict(zip(d, vals)) for vals in zip(*d.values())]
Result:
[{'n': 'a', 'a': 1, 'p': '123'}, {'n': 'b', 'a': 2, 'p': '321'}, {'n': 'x', 'a': 3, 'p': '456'}]
Use:
res = [dict(v) for v in zip(*[[(key, value) for value in values] for key, values in d.items()])]
print(res)
Output
[{'n': 'a', 'a': 1, 'p': '123'}, {'n': 'b', 'a': 2, 'p': '321'}, {'n': 'x', 'a': 3, 'p': '456'}]
A simpler alternative approach is to do:
result = [{} for _ in range(len(d))]
for key, values in d.items():
for i, value in enumerate(values):
result[i][key] = value
print(result)
Output (alternative)
[{'n': 'a', 'a': 1, 'p': '123'}, {'n': 'b', 'a': 2, 'p': '321'}, {'n': 'x', 'a': 3, 'p': '456'}]
Let's work through the problem step by step.
The core difficulty is that we have a sequence of lists:
['a', 'b', 'x']
[1, 2, 3]
['123', '321', '456']
And we want to produce sequences consisting of element 0 of each list, element 1 of each list, etc. (Each of these sequences contains all the values for an output dict.) Which is to say, we want to transpose the lists, which is exactly what the built-in zip is for:
# Feed the generator to `list` to unpack and view them
list(zip(
['a', 'b', 'x'],
[1, 2, 3],
['123', '321', '456']
))
Now we can sketch out a complete process:
Get the keys and values of the input (in the same order).
Transpose the values.
For each sequence in the transposed values, match that sequence up with the keys to make a new dict.
The first two parts are easy:
keys, value_lists = d.keys(), d.values()
# Since the .values() are a sequence, while `zip` accepts multiple
# arguments, we need to use the `*` operator to unpack them as
# separate arguments.
grouped_values = zip(*value_lists)
To finish up, let's first figure out how to create a single result dict from a single one of the new_values. It's easy to make a dict from a bunch of key-value pairs - we can feed that directly to dict. However, we have instead a pair of sequences - the original .keys(), and a result from the zip. Clearly, the solution is to zip again - we can make a trivial helper function to make sure everything is as clear as possible:
def new_dict(keys, values):
return dict(zip(keys, values))
Then all we need to do is repeatedly apply that function:
new_dicts = [new_dict(keys, values) for values in grouped_values]
Putting everything inline with short names for the sake of showing off gives:
new_dicts = [dict(zip(d.keys(), v)) for v in zip(*d.values())]
which is almost exactly Jab's answer (note that iterating over a dictionary gives the keys, so you can pass d directly rather than d.keys() to zip since zip will only be iterating over it).
Good Question.
Conversion from one data type to other is essential in either development or competitive programming.
It can be done in many methods, I'm explaining the two methods which I know, below:
Method #1 : Using list comprehension
We can use list comprehension as the one-liner alternative to perform various naive tasks providing readability with a more concise code. We can iterate through each of dictionary element and corresponding keep constructing the list of dictionary.
# Python3 code to demonstrate
# to convert dictionary of list to
# list of dictionaries
# using list comprehension
# initializing dictionary
test_dict = { "Rash" : [1, 3], "Manjeet" : [1, 4], "Akash" : [3, 4] }
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# using list comprehension
# to convert dictionary of list to
# list of dictionaries
res = [{key : value[i] for key, value in test_dict.items()}
for i in range(2)]
# printing result
print ("The converted list of dictionaries " + str(res))
Method #2 : Using zip()
This approach used zip function two times, first time when we need to zip the particular index value of all lists as one and second to get all values of particular index and zip it with the corresponding keys.
# Python3 code to demonstrate
# to convert dictionary of list to
# list of dictionaries
# using zip()
# initializing dictionary
test_dict = { "Rash" : [1, 3], "Manjeet" : [1, 4], "Akash" : [3, 4] }
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# using zip()
# to convert dictionary of list to
# list of dictionaries
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())]
# printing result
print ("The converted list of dictionaries " + str(res))
Output
The original dictionary is : {‘Rash’: [1, 3], ‘Manjeet’: [1, 4], ‘Akash’: [3, 4]}
The converted list of dictionaries [{‘Rash’: 1, ‘Manjeet’: 1, ‘Akash’: 3}, {‘Rash’: 3, ‘Manjeet’: 4, ‘Akash’: 4}]
I have a list of dictionaries with different amounts of keys/values, I cant change the list because its extracted from another program over which I have no control:
l = [{'a': 123, 'b': 234, 'c': 'approved'}, {'a': 456, 'b': 567}, {'a': 678, 'b': 789, 'c': 'approved'}]
I want to get a list of values for key 'a' where the key 'c' == 'approved', if I try:
approved_list = [i['a'] for i in l if i['c'] == 'approved']
I get the error: KeyError: 'c' I assume because dict[1] has no key 'c'.
I tried to get the list of dictionaries to only include those with key 'c' like this:
dicts_with_approval = [i for i in l if i.keys() == 'c']
but that just gives an empty list [].
Help appreciated.
You can use dict.get instead to provide a value if the key lookup fails:
[i['a'] for i in l if i.get('c') == 'approved']
# [123, 678]
You can modify your answer like this (check whether "c" is in the keys of the dict:
approved_list = [i['a'] for i in l if "c" in i.keys() if i['c'] == 'approved' ]
Your approach here is slightly incorrect
[i for i in l if i.keys() == 'c']
You are trying to check if the list which is i.keys() is equal to a single key element c which will never be true. Therefore, it should be other way round, you need to check if the key c is present in the dictionary i.keys().
Change to your existing code
[i['a'] for i in l if 'c' in i.keys() and 'approved'==i['c']] # [123, 678]
I'm trying to invert a simple dictionary like:
{'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
I'm using this function:
def invert(d):
return dict([(x,y) for y,x in d.iteritems()])
Now when I invert my dictionary, everything works out fine. When I invert it twice however, I get:
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
which is not in the same order as the dictionary I started with. Is there a problem with my invert function? Sorry I'm kinda new to python, but thanks for any help!
That is correct, dictionaries are unordered in python
from another so answer answer:
CPython implementation detail: Keys and values are listed in an
arbitrary order which is non-random, varies across Python
implementations, and depends on the dictionary’s history of insertions
and deletions.
from the docs:
It is best to think of a dictionary as an unordered set of key: value
pairs, with the requirement that the keys are unique (within one
dictionary). A pair of braces creates an empty dictionary: {}. Placing
a comma-separated list of key:value pairs within the braces adds
initial key:value pairs to the dictionary; this is also the way
dictionaries are written on output.
Python dictionaries are unsorted by design.
You can use collections.OrderedDict instead if you really need this behaviour.
Try running this code:
d = {
'a' : 1, 'b' : 2,
'c' : 3, 'd' : 4
}
def invert(d):
return dict([(x,y) for y,x in d.iteritems()])
print d
d = invert(d)
print d
d = invert(d)
print d
This is the output:
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
As you can see, it technically is the same dictionary, but when you declare it, it is unordered.