I am making a simple program and need help.
memory = {'a': 'a', 'b': 'b'}
for key, value in memory.items():
print(key)
I need to target a specific key like this: x = '2', memory = {'a': '1', 'b': '2'}, for k, v in memory.items(x):, print(k). My idea is that the x should decide which key should be printed by it's value.
I'm not entirely sure what your asking for, but do you want to print the value?
memory = {'a': 'A', 'b': 'B'}
for key, value in memory.items():
print('key = {}'.format(key))
print('value = {}'.format(value))
or only the b value?
print(memory['b'])
or do you want to print the key for which the value is B?
for key, val in memory.items():
if val == 'B':
print('key = {}'.format(key))
Use keys() method to get list keys and then iterate over them in the for loop
memory = {'a': 'a', 'b': 'b'}
for key in memory.keys():
print(key)
# if you need the corresponding value
print(memory[key])
Related
I need to combine two dictionaries by their value, resulting in a new key which is the list of keys with the shared value. All I can find online is how to add two values with the same key or how to simply combine two dictionaries, so perhaps I am just searching in the wrong places.
To give an idea:
dic1 = {'A': 'B', 'C': 'D'}
dic2 = {'D': 'B', 'E': 'F'}
Should result in:
dic3 = {['A', 'D']: 'B', 'C': 'D', 'E': 'F'}
I am not sure why you would need such a data structure, you can probably find a better solution to your problem. However, just for the sake of answering your question, here is a possible solution:
dic1 = {'A':'B', 'C':'D'}
dic2 = {'D':'B', 'E':'F'}
key_list = list(dic2.keys())
val_list = list(dic2.values())
r = {}
for k,v in dic1.items():
if v in val_list:
i = val_list.index(v) #get index at value
k2 = key_list[i] #use index to retrive the key at value
r[(k, k2)] = v #make the dict entry
else:
r[k] = v
val_list = list(r.values()) #get all the values already processed
for k,v in dic2.items():
if v not in val_list: #if missing value
r[k] = v #add new entry
print(r)
output:
{('A', 'D'): 'B', 'C': 'D', 'E': 'F'}
You can't assign a list as a key in a python dictionary since the key must be hashable and a list is not an ashable object, so I have used a tuple instead.
I would use a defaultdict of lists and build a reversed dict and in the end reverse it while converting the lists to tuples (because lists are not hashable and can't be used as dict keys):
from collections import defaultdict
dic1 = {'A':'B', 'C':'D'}
dic2 = {'D':'B', 'E':'F'}
temp = defaultdict(list)
for d in (dic1, dic2):
for key, value in d.items():
temp[value].append(key)
print(temp)
res = {}
for key, value in temp.items():
if len(value) == 1:
res[value[0]] = key
else:
res[tuple(value)] = key
print(res)
The printout from this (showing the middle step of temp) is:
defaultdict(<class 'list'>, {'B': ['A', 'D'], 'D': ['C'], 'F': ['E']})
{('A', 'D'): 'B', 'C': 'D', 'E': 'F'}
If you are willing to compromise from 1-element tuples as keys, the second part will become much simpler:
res = {tuple(value): key for key, value in temp.items()}
I have a dictionary dict_matches with 2 inner dictionaries.
The structure of dict_match is as follows:
dict_match = {Query_ID:{Function_ID:{DB_ID:[func_ID]}}}
Within the top level of keys Query_ID, I loop through these and compare these against keys in a completely separate dict query_count_dict to determine the overlap of keys.
Within this loop I also navigate to the base dict in dict_matches in order to see what keys DB_ID the master key has 'matched' with. My problem is that this lower-level of keys DB_ID that correspond to the very top-level key Query_ID can be duplicated (and I only want to see the unique keys). I tried using the set() method but this actually split the string keys into their character components and printed the unique characters for each lower-level key. Any help appreciated!
See code below
for k,v in dict_match.items():
if k in query_count_dict.keys():
print(k)
detection_query.append(k)
print(len(dict_match[k])/int(query_count_dict[k]))
if type(v) is dict:
recursive_items(v)
where recursive_items is a function to navigate to the base dict:
def recursive_items(dictionary):
for k, v in dictionary.items():
if type(v) is dict:
recursive_items(v)
else:
print(set(k))
You can print all the unique keys by passing a list of keys in your recursive function, to store them as you navigate to the base. Then cast it to set to remove the duplicates.
def get_keys(dictionary, keys=[]):
for k, v in dictionary.items():
keys.append(k)
if isinstance(v, dict):
get_keys(v, keys)
return set(keys)
dict_match = {'A': {'A': {'B': [0], 'H': [0]}, 'D': {'C': [0], 'A': [0]}},
'B': {'C': {'A': [0]}, 'G': {'A': [0]}},
'C': {'A': {'E': [0]}, 'B': {'F': [0], 'A': [0]}, 'C': {'B': [0]}}}
print(get_keys(dict_match))
And it will output only the unique keys:
{'G', 'B', 'E', 'F', 'C', 'H', 'A', 'D'}
The following is my dictionary and I need to check if I have repeated key or Value
dict = {' 1': 'a', '2': 'b', '3': 'b', '4': 'c', '5': 'd', '5': 'e'}
This should return false or some kind of indicator which helps me print out that key or value might be repeated. It would be much appreciated if I am able to identify if a key is repeated or a Value (but not required).
Dictionaries can't have duplicate keys, so in case of repeated keys it only keeps the last value, so check values (one-liner is your friend):
print(('There are duplicates' if len(set(dict.values()))!=len(values) else 'No duplicates'))
Well in a dictionary keys can't repeat so we only have to deal with values.
dict = {...}
# get the values
values = list(dict.values())
And then you can use a set() to check for duplicates:
if len(values) == len(set(values)): print("no duplicates")
else: print("duplicates)
It's not possible to check if a key repeats in a dictionary, because dictionaries in Python only support unique keys. If you enter the dictionary as is, only the last value will be associated with the redundant key:
In [4]: dict = {' 1': 'a', '2': 'b', '3': 'b', '4': 'c', '5': 'd', '5': 'e'}
In [5]: dict
Out[5]: {' 1': 'a', '2': 'b', '3': 'b', '4': 'c', '5': 'e'}
A one-liner to find repeating values
In [138]: {v: [k for k in d if d[k] == v] for v in set(d.values())}
Out[138]: {'a': [' 1'], 'b': ['2', '3'], 'c': ['4'], 'e': ['5']}
Check all the unique values of the dict with set(d.values()) and then creating a list of keys that correspond to those values.
Note: repeating keys will just be overwritten
In [139]: {'a': 1, 'a': 2}
Out[139]: {'a': 2}
What about
has_dupes = len(d) != len(set(d.values()))
I'm on my phone so I cant test it. But j think it will work.
Well, although key value should be unique according to the documentation, there is still condition where repeated key could appear.
For example,
>>> import json
>>> a = {1:10, "1":20}
>>> b = json.dumps(a)
>>> b
'{"1": 20, "1": 10}'
>>> c = json.loads(b)
>>> c
{u'1': 10}
>>>
But in general, when python finds out there's conflict, it takes the latest value assigned to that key.
For your question, you should use comparison such as
len(dict) == len(set(dict.values()))
because set in python contains an unordered collection of unique and immutable objects, it could automatically get all unique values even when you have duplicate values in dict.values()
I have an object and the I want to find the value is None.
And the next step I want to delete the key.
I try this way:
>>> obj = {'a': '1', 'b': '2', 'c': '3', 'd': None, 'e': '4', 'f': None }
>>> keys = list(obj.keys())
>>> for key in keys:
... if obj[key] == None:
... obj.pop(key, None)
>>> obj
{'a': '1', 'b': '2', 'c': '3', 'e': '4'}
Is there a better way to do this?
You could use a dictionary comprehension:
obj = {k: v for k, v in obj.items() if v is not None}
If you don't want to replace the dictionary wholesale (because perhaps you have other references to it), then your approach is sound, but can be made a little more efficient still by avoiding calling .keys(), and using del instead of dict.pop():
for key in list(obj):
if obj[key] is None:
del obj[key]
Testing for None should always be done with is; it's a singleton object.
This question already has answers here:
How can one make a dictionary with duplicate keys in Python?
(9 answers)
Closed 6 months ago.
Good day all,
I am trying to convert a list of length-2 items to a dictionary using the below:
my_list = ["b4", "c3", "c5"]
my_dict = {key: value for (key, value) in my_list}
The issue is that when a key occurrence is more than one in the list, only the last key and its value are kept.
So in this case instead of
my_dict = {'c': '3', 'c': '5', 'b': '4'}
I get
my_dict = {'c': '5', 'b': '4'}
How can I keep all key:value pairs even if there are duplicate keys.
Thanks
For one key in a dictionary you can only store one value.
You can chose to have the value as a list.
{'b': ['4'], 'c': ['3', '5']}
following code will do that for you :
new_dict = {}
for (key, value) in my_list:
if key in new_dict:
new_dict[key].append(value)
else:
new_dict[key] = [value]
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}
Same thing can be done with setdefault. Thanks #Aadit M Shah for pointing it out
new_dict = {}
for (key, value) in my_list:
new_dict.setdefault(key, []).append(value)
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}
Same thing can be done with defaultdict. Thanks #MMF for pointing it out.
from collections import defaultdict
new_dict = defaultdict(list)
for (key, value) in my_list:
new_dict[key].append(value)
print(new_dict)
# output: defaultdict(<class 'list'>, {'b': ['4'], 'c': ['3', '5']})
you can also chose to store the value as a list of dictionaries:
[{'b': '4'}, {'c': '3'}, {'c': '5'}]
following code will do that for you
new_list = [{key: value} for (key, value) in my_list]
If you don't care about the O(n^2) asymptotic behaviour you can use a dict comprehension including a list comprehension:
>>> {key: [i[1] for i in my_list if i[0] == key] for (key, value) in my_list}
{'b': ['4'], 'c': ['3', '5']}
or the iteration_utilities.groupedby function (which might be even faster than using collections.defaultdict):
>>> from iteration_utilities import groupedby
>>> from operator import itemgetter
>>> groupedby(my_list, key=itemgetter(0), keep=itemgetter(1))
{'b': ['4'], 'c': ['3', '5']}
You can use defaultdict to avoid checking if a key is in the dictionnary or not :
from collections import defaultdict
my_dict = defaultdict(list)
for k, v in my_list:
my_dict[k].append(v)
Output :
defaultdict(list, {'b': ['4'], 'c': ['3', '5']})