python dictionaries values and keys [duplicate] - python

This question already has answers here:
How to filter a dictionary according to an arbitrary condition function?
(7 answers)
Closed 4 years ago.
I've got dictionary called humans. I want to loop through that dictionary and if value is less than 20 print dictionary key.
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}

Your description of the problem is almost a perfect pseudo-code for how you would implement that:
# I've got dictionary called humans.
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
for key, value in humans.items(): # I want to loop through that dictionary
if value < 20: # and if value is less than 20
print(key) # print dictionary key.

Try this:
for k, v in humans.items():
if v > 20:
print(k)
Or, a more pythonic way:
print([k for k, v in humans.items() if v > 20])

Try this, using generator expressions:
result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))
I used commas as separators, if you need each item in a different line simply substitute ', ' with '\n'.

Loop over items().
You can use comprehension (no need to use [ ] as it is in parenthesis already):
print(k for k,v in humans.items() if v > 20)
or really loop:
for k,v in humans.items():
if v > 20:
print(k)

Related

Assign values of a nested dictionary to variables named after the keys

I'm trying to assign the values of a nested dictionary to variables named after their key. I found this code on Stackoverflow but it only prints the key and value pair:
def myprint(d):
for k, v in d.items():
if isinstance(v, dict):
myprint(v)
else:
print("{0} : {1}".format(k, v))
I would like it so that for example, if I have the following in my dictionary: {thisIsADummy : 37}
I can somehow create a variable named thisIsADummy, named after the key, with the value 37
So my input ould be print(thisIsADummy) and the output would be 37
Please let me know if anybody has any ideas on how to do this as efficiently as possible, because this dictionary has probably over a thousand pairs. Thank you.
EDIT:
Using exec works well, but I oversimplified in the original post. I need the variable to be a dictionary so when I open multiple files I can append values.
Basic idea is to use 'exec' function like below.
nat = {
'abc': 1,
'a123': 2,
'a1b': 3,
'b31': 4
}
for k, v in nat.items():
exec("%s = %d" % (k, v))
print(k, v)
print(abc, a123, a1b, b31)
Note: It will only work if keys follows the variable name constraints
Avoid using eval(),Try setattr(I am not sure whether it is a better way.):
import sys
d = {"thisIsADummy": 37, 'a': [123,2]}
for k, v in d.items():
setattr(sys.modules[__name__], k, v)
a.append(1)
print(thisIsADummy, a)
Result:
37 [123, 2, 1]

How flatten semi nested python dictionary [duplicate]

This question already has answers here:
Flatten nested dictionaries, compressing keys
(32 answers)
Closed 3 years ago.
I have a python dictionary like following:
score_dictionary={'Agriculture':89,'Health':{'Public':90,'Private':78},'Mines':70,'Commerce':67}
Using this dictionary, I want to convert to the following:
score_dictionary={'Agriculture':89,'Health_public':90,'Health_Private':78,'Mines':70,'Commerce':67}
Now I'm stuck at how to convert it?
You could use isinstance to check whether or not the value in a given key/value pair consist in another dictionary, format the key name with string formatting and update accordingly:
d = {}
for k,v in score_dictionary.items():
if not isinstance(v, dict):
d[k] = v
else:
for k_, v_ in v.items():
d[f'{k}_{k_}'] = v_
print(d)
{'Agriculture': 89,
'Health_Public': 90,
'Health_Private': 78,
'Mines': 70,
'Commerce': 67}

How to get the key from value in a dictionary in Python? [duplicate]

This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 5 years ago.
d[key] = value
but how to get the keys from value?
For example:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
You can write a list comprehension to pull out the matching keys.
print([k for k,v in a.items() if v == b])
Something like this can do it:
for key, value in a.iteritems():
if value == 10:
print key
If you want to save the associated keys to a value in a list, you edit the above example as follows:
keys = []
for key, value in a.iteritems():
if value == 10:
print key
keys.append(key)
You can also do that in a list comprehension as pointed out in an other answer.
b = 10
keys = [key for key, value in a.iteritems() if value == b]
Note that in python 3, dict.items is equivalent to dict.iteritems in python 2, check this for more details: What is the difference between dict.items() and dict.iteritems()?

Sorting by value in a python dictionary? [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 8 years ago.
I have an assignment in which a series of items and the amount a store carries of that item is given which I then have to put into a dictionary and display with the highest amount of stock to the lowest amount of stock.
The dictionary looks a bit like this:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
and the output would look like this:
keyboards: 56
hammers: 33
socks: 10
After getting the dictionary set up, I'm having difficulty with the second part... does anyone know how I could sort by value?
It's easy to make a sorted list of (key, value) pairs:
import operator
slop = sorted(thelist.items(), key=operator.itemgetter(1), reverse=True)
and then you can loop over it to display it, e.g in Python 2:
for k, v in slop:
print '{}: {}'.format(k, v),
print
To sort you can use sorted method:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
sorted_items = sorted(items.items(), key=lambda v: v[1], reverse = True)
As a key you specify to sort by value in the items dict. And to print it, you can just use:
for k,v in sorted_items:
print("{}:{}".format(k,v))

The best way to filter a dictionary in Python [duplicate]

This question already has answers here:
How to filter a dictionary according to an arbitrary condition function?
(7 answers)
Closed 7 years ago.
I have a dictionary of string keys and float values.
mydict = {}
mydict["joe"] = 20
mydict["bill"] = 20.232
mydict["tom"] = 0.0
I want to filter the dictionary to only include pairs that have a value greater than zero.
In C#, I would do something like this:
dict = dict.Where(r=>r.Value > 0);
What is the equivalent code in Python?
d = dict((k, v) for k, v in d.iteritems() if v > 0)
In Python 2.7 and up, there's nicer syntax for this:
d = {k: v for k, v in d.items() if v > 0}
Note that this is not strictly a filter because it does create a new dictionary.
Assuming your original dictionary is d1 you could use something like:
d2 = dict((k, v) for k, v in d1.items() if v > 0)
By the way, note that dict is already reserved in python.
The dict constructor can take a sequence of (key,value) pairs, and the iteritems method of a dict produces a sequence of (key,value) pairs. It's two great tastes that taste great together.
newDict = dict([item for item in oldDict.iteritems() if item[1] > 0])
foo = {}
foo["joe"] = 20
foo["bill"] = 20.232
foo["tom"] = 0.0
bar = dict((k,v) for k,v in foo.items() if v>0)
dict is a keyword in Python so I replaced it with foo.
first of all you should not use the keyword dict as a variable name as it pollutes the namespace, and prevents you from referencing the dict class in the current or embedded scope.
d = {}
d["joe"] = 20
d["bill"] = 20.232
d["tom"] = 0.0
# create an intermediate generator that is fed into dict constructor
# via a list comprehension
# this is more efficient that the pure "[...]" variant
d2 = dict(((k, v) for (k, v) in d.iteritems() if v > 0))
print d2
# {'bill': 20.232, 'joe': 20}
Alternatively, you could just create the generator and iterator over it directly. This more like a "filter", because the generator only references the values in the original dict instead of making a subset copy; and hence is more efficient than creating a new dictionary :
filtered = ((k, v) for (k, v) in d.iteritems() if v > 0)
print filtered
# <generator object <genexpr> at 0x034A18F0>
for k, v in filtered:
print k, v
# bill 20.232
# joe 20
try
y = filter(lambda x:dict[x] > 0.0,dict.keys())
the lambda is feed the keys from the dict, and compares the values in the dict for each key, against the criteria, returning back the acceptable keys.

Categories

Resources