I want to change a dictionary's all values to 1 (float), I did research online but it seems people rarely have this random need.
The dictionary has thousands of entries, below is part of it
{
'2015': [2.8216107792591907],
'2016': [2.3686578052627687],
'2017': [2.03069274701226]
}
Can someone give me some ideas ? Thank you!
myDict = {key : 1.0 for key in myDict}
for element in my_dict:
my_dict[element] = 1.0
You can try this:
d = {x: 1.0 for x in d}
That creates a new dictionary d that maps every key in d (the old one) to 1.
I believe using iterkeys() is much efficient.
for k in d.iterkeys():
d[k] = [1.0]
You can also do the same without any loops and in a single line using fromkeys():
d = d.fromkeys(d, [1.0])
Hope it helps!!
Related
I have a list of dictionaries and I have a solution, described below:
[{"A1":"B1", "C1":"D1"},{"A2":"B2", "C2":"D2"},....]
Expected output would be a dictionary like this
{
"B1":"D1",
"B2":"D2",
...
}
My current procedure is
get one dictionary and create a 2 entries dict to a single one
input:
{"A1":"B1", "C1":"D1"}
output:
{"B1":"D1"}
where the "A1" and "C1" is inside my method configureable:
def method(input_dictionary, default_key_from_dict, default_value_from_dict):
single_dictionary[input_dictionary[default_key_from_dict]] = input_dictionary[default_value_from_dict]
later I perform the following ones:
def function(dict_list):
single_key_value_dictionary_list = list(map(convert_two_entries_dictionary_to_one_by_value, dict_list))
global_dict = reduce(lambda a, b: dict(a, **b), single_key_value_dictionary_list)
return global_dict
I ask myself if there is some better solution for this, I have the generator idea in my mind but I am not sure if it is worth to think about it? Any remarks on this?
UPDATE
There are only 2 keys in each entry of the list as dictionary. 2 keys only.
BR Peter
From the comments since you always have only 2 keys. You can use dict.update.
inp=[{"A1":"B1", "C1":"D1"},{"A2":"B2", "C2":"D2"}]
out={}
for d in inp:
out.update((d.values(),))
out
# {'B1': 'D1', 'B2': 'D2'}
You can use something about this:
dict1 = {"A1":"B1", "C1":"D1"}
it = iter(dict1.values())
list1 = list(zip(it, it))
print(list1)
i am new in python.I just working with the list and dictionary.I am looking for take a list value under key in a dictinary and want to show output the values of list under the associated key.for example,
if i have a list of different car name's such as
list = ['Toyota','Ferrery','Ford','Nisshan']
then i just want to take the list values in a dictionary under single key such as,
dict = {'Car_name': list_values }
how can i do that and how can i make an output such as
Car_name : Toyota , Ferrary , Ford , Nisshan.
hope all you understand my question.
please help me out to fix the problem.
Well, one can simply make a dict like so:
l = ['Toyota','Ferrery','Ford','Nisshan']
d = {'Car Names': l}
As for getting the output right:
l = ['Toyota', 'Ferrery', 'Ford', 'Nisshan']
d = {'Car Names': l}
for key, value in d.items():
print(key, ':', str(value)[1:-1])
just for understanding
l = ['Toyota','Ferrery','Ford','Nisshan']
dictionary = {}
dictionary['Car_Names']=l #the value of key 'Car_Names ' would be the list l
print dictionary #it will give the result as u have asked
i hope it helps
Can you guys think of any one liners equal to if/else statements:
d = dict()
key = 1, 2
if key in d:
d[key]['idx'] += [2]
else:
d[key] = {'idx': [2]}
print d
?
EDIT:
Thanks guys. You narrowed me to collection.defaultdict & dict.setdafault and with this in mind I was able to achieve what I wanted:
from collections import defaultdict
d = dict()
key = 1, 2
d.setdefault(key, {'idx': []})
d[key]['idx'] += [2]
Maybe it is not one liner as it spreads over 2 lines (setdefault() call and then in place addition), but looks nicer though.
But still, if anyone have any ideas how to make it real one liner please share it.
Sometimes it is better to do things in multiple lines, this is one of those cases. However sometimes it is reasonable to try to avoid this sort of "does this key exist" logic, and to do that you can use collections.defaultdict or dict.setdefault(). And now just for fun, here is a horrible one-liner that you should not use (but is equivalent in behavior to your if/else):
d.setdefault(key, {'idx': []})['idx'] += [2] if d[key]['idx'] else [1]
Note that this is less efficient than your original version, because it requires additional lookups, and creates unnecessary objects each time you use it.
Maybe:
d = dict()
key = 1,2
d[key] = (d[key]['idx'] + [2] if key in d and 'idx' in d[key] else {'idx': [2]})
key=1,2
d={key:'idx'}
d[key]['idx'] = d[key]['idx']+[2] if key in d else ['2']
Is it possible to replace all values in a dictionary, regardless of value, with the integer 1?
Thank you!
Sure, you can do something like:
d = {x: 1 for x in d}
That creates a new dictionary d that maps every key in d (the old one) to 1.
You can use a dict comprehension (as others have said) to create a new dictionary with the same keys as the old dictionary, or, if you need to do the whole thing in place:
for k in d:
d[k] = 1
If you're really fond of 1-liners, you can do it in place using update:
d.update( (k,1) for k in d )
a = {1:2, 2:2,3:2}
a = {x:1 for (x,_) in a.iteritems()}
print a
{1: 1, 2: 1, 3: 1}
Yes, it's possible. Iterate through every key in the dictionary and set the related value to 1.
I have one defaultdict(list) and other normal dictionary
A = {1:["blah", "nire"], 2:["fooblah"], 3:["blahblah"]}
B = {1: "something" ,2:"somethingsomething"}
now lets say that i have something like this
missing_value = "fill_this"
Now, first I want to find what are the keys in B missing from A (like 3 is missing)
and then set those keys to the values missing_value?
What is the pythonic way to do this?
Thanks
You can use setdefault:
for k in A:
B.setdefault(k, "fill_this")
This is essentially the same as the longer:
for k in A:
if k not in B:
B[k] = "fill_this"
However, since setdefault only needs to lookup each k once, setdefault is faster than this "test&set" solution.
Alternatively (and probably slower), determine the set difference and set (no pun intended) those values:
for k in set(A).difference(B):
B[k] = "fill_this"
The solution is to go through A and update B where necessary. It would have O(len(A)) complexity:
for key in A:
if key not in B:
B[key] = missing_value
Here's one way:
def test():
A = {1:"blah", 2:"fooblah", 3:"blahblah"}
B = {1: "something" ,2:"somethingsomething"}
keys=set(A.keys()).difference(set(B.keys()))
for k in keys:
B[k]="missing"
print (B)
When I've seen a need for this, there were a standard set of keys to be checked in a dict of dicts. If that's the case and if performance is not a significant factor, I think this is the cleanest syntax.
template = {k: default for k in domain}
for k, d in dicts.items():
dicts[k] = template.copy().update(d)