Constructing a new dict:
dict_you_want = {key: old_dict[key] for key in your_keys}
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Answer from user395760 on Stack OverflowConstructing a new dict:
dict_you_want = {key: old_dict[key] for key in your_keys}
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
Pick a key from a dictionary python - Stack Overflow
python - How to select keys from a dictionary by their order? - Stack Overflow
python - How to select only specific key-value pairs from a list of dictionaries? - Stack Overflow
Select the key:value pairs from a dictionary in Python - Stack Overflow
I have the following dictionary that contains 5 keys.
dic1={'key1': ['test1', 99.172, 0.456], 'key2': ['test2', 99.473, 0.366], 'key3': ['test3', 99.278, 0.583], 'key4': ['test4', 99.773, 0.207], "key5":['test5', 92.172, 0.486]}My question is:
How do I select the key from the dictionary where the 3rd value, is closest to 0.5 ?
in this case the result should be
result={"key5":['test5', 92.172, 0.486]}
You can use the .keys() method:
for key in myDictionary.keys():
print(key)
You can also use .items() to iterate through both at the same time:
for key, value in myDictionary.items():
print(key, value)
You can iterate over the keys of a dict with a for loop:
>>> for key in yourdict:
>>> print(key)
hi
hello
If you want them as a comma separated string you can use ', '.join.
>>> print(', '.join(yourdict))
hi, hello
on a similar note is there a way to say myDictionary.key1 and that will return hi
No. The keys in a dictionary are not in any particular order. The order that you see when you iterate over them may not be the same as the order you inserted them into the dictionary, and also the order could in theory change when you add or remove items.
if you need an ordered collection you might want to consider using another type such as a list, or an OrderedDict
This is probably what you were looking for.
Note this is for Python 3.7 and forward.
d = {1: 'a', 2: 'b'} # dict is a bad variable name! don't do it! it overrides a built-in!
d_keys = list(d.keys())
first_value = d[d_keys[0]]
Dictionaries cannot be used like lists, in that you cannot refer to their position. However, you can use something like this to get the keys from your dictionary:
my_dict = {1: 'a', 2: 'b'}
for k in my_dict:
print(k)
print(my_dict[k])
Output:
1
a
2
b
You can try something like this:
In [1]: dictlist = [{'Name': 'James', 'city': 'paris','type': 'A' },
...: {'Name': 'James','city': 'Porto','type': 'B'},
...: {'Name': 'Christian','city': 'LA','type': 'A'}]
In [2]: keys = ["Name","type"]
In [3]: res = []
In [5]: for dict1 in dictlist:
...: result = dict((k, dict1[k]) for k in keys if k in dict1)
...: res.append(result)
...:
In [6]: res
Out[6]:
[{'Name': 'James', 'type': 'A'},
{'Name': 'James', 'type': 'B'},
{'Name': 'Christian', 'type': 'A'}]
It's a bit more complicated than this answer but you can also use zip and itemgetter.
In [43]: list_of_dicts = [
...: {"a":1, "b":1, "c":1, "d":1},
...: {"a":2, "b":2, "c":2, "d":2},
...: {"a":3, "b":3, "c":3, "d":3},
...: {"a":4, "b":4, "c":4, "d":4}
...: ]
In [44]: allowed_keys = ("a", "c")
In [45]: filter_func = itemgetter(*allowed_keys)
In [46]: list_of_filtered_dicts = [
...: dict(zip(allowed_keys, filter_func(d)))
...: for d in list_of_dicts
...: ]
In [47]: list_of_filtered_dicts
Out[47]: [{'a': 1, 'c': 1}, {'a': 2, 'c': 2}, {'a': 3, 'c': 3}, {'a': 4, 'c': 4}]
If you truly want to create a new dictionary with the keys in your list, then you can use a dict comprehension.
a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b = ["b", "c"]
out = {x: a[x] for x in b}
This will fail by raising a KeyError if any of the elements of b are not actually keys in a.
If you don't have any problem with modifing the exsisting dict then try this :
out = {}
for key in b:
out[key] = a.pop(key)
This wouldn't take any extra space, as we're transferring the values required from old to new dict, and would solve the problem of slow selective popping as well(as we're not traversing through all but only the selective one's which are required).
If you are checking each keys value, simply check all values:
if input_a not in dictionary.values():
print('Sorry, try again')
If you have iterables as values:
if not any(input_a in ele for ele in dictionary.values()):
print('Sorry, try again')
I used any as I presume if input_a was equal to 2 and some keys value was equal to [1,2,3] then it should return True.
the all solution is the best. I just want to add an answer that only adds a line to your code:
for key in dictionary.keys():
if input_a not in dictionary[key]:
print('Sorry, try again')
I think you're misunderstanding what filter() does. From the docs:
filter(function, iterable):
Construct an iterator from those elements of iterable for which function returns true.
So when you do
hits = dict(filter(lambda item: 'hit' in item[0], topHitsDict['record301'].items()))
You're essentially doing:
hits = {}
for item in topHitsDict['record301'].items():
if 'hit' in item[0]:
hits[item[0]] = item[1]
which gives you only the hit* keys from topHitsDict['record301'].
hits = {'hit1': {'description': 'OBGP-2018-240_Oncorhynchus.clarkii',
'score': '340',
'eval': '2e-94'},
'hit2': {'description': 'OBGP-2017-332_Oncorhynchus.clarkii',
'score': '340',
'eval': '2e-94'}}
Instead, what you actually want is the description from those hit* dicts. For this, you can use map, and then convert the iterator to a list.
descriptions = list(map(lambda item: item[1]['description'], hits.items())
# descriptions: ['OBGP-2018-240_Oncorhynchus.clarkii', 'OBGP-2017-332_Oncorhynchus.clarkii']
This is equivalent to:
descriptions = []
for item in hits.items():
descriptions.append(item[1]['description'])
And if you want to do this for all keys of topHitsDict, you'd have to change it up a bit. Either using a loop:
all_descriptions = []
for recordVal in topHitsDict.values():
hits = dict(filter(lambda item: 'hit' in item[0], recordVal.items()))
descriptions = list(map(lambda item: item[1]['description'], hits.items())
# Add to all_descriptions
all_descriptions = all_descriptions + descriptions
It's almost always easier to write these out as a loop first. Then you can write them as a list- or dict- comprehension, and then use filter() and map()
all_descriptions = []
for record in topHitsDict.values():
for hitname, hitval in record.items():
if "hit" in hitname:
all_descriptions.append(hitval['description'])
Or as a comprehension:
all_descriptions = [hitval["description"] for record in topHitsDict.values() for hitname, hitval in record.items() if "hit" in hitname]
You will require 2 loops to complete this unless you insist on processing every recordxxx key separately using 1 loop.
And also list comprehensions are a little bit easier to read/understand than filter.
desc = [
v["description"]
for _, value in topHitsDict.items()
for k, v in value.items()
if "hit" in k
]