my_dict={'reportName': 'sale_order', 'extract_extractType': 'sales', 'extract_stages_load_output_tableName': 'extract_table_name',
'extract_stages_load_clientMarket_tableFilters_0': 'client_mkt_version_id|1',
'extract_stages_load_clientMarket_tableFilters_1': 'client_mkt_short_name|HCV_NOVEL',
'extract_stages_load_clientMarket_tableFilters_2': 'client_Id|161'}
case1:
kv=['extract', 'output']
Now my question is if all list elements present on dictionary then display key and value and dict.
output: 'extract_stages_load_output_tableName': 'extract_table_name'.
case2:
if list elements contains tableFilters
kv=['extract','clientMarket','tableFilters','client_mkt_short_name']
output: 'extract_stages_load_clientMarket_tableFilters_1': HCV_NOVEL
same way for remaining
{'extract_stages_load_clientMarket_tableFilters_0': 1,
'extract_stages_load_clientMarket_tableFilters_1': 'HCV_NOVEL',
'extract_stages_load_clientMarket_tableFilters_2': 161'}
def get_key(key, kv):
return len(set(kv) - set(key.split('_'))) == 0
{k: v for k, v in my_dict.items() if get_key(k, kv)}
{'extract_stages_load_output_tableName': 'extract_table_name'}
Edit
def get_key(key, kv):
return all([_kv in s for _kv in kv])
{k: v for k, v in my_dict.items() if get_key(k, kv)}
{'extract_stages_load_output_tableName': 'extract_table_name'}
In case you are not searching for specific words in underscore-separted strings:
my_dict={'reportName': 'sale_order', 'extract_extractType': 'sales',
'extract_stages_load_output_tableName': 'extract_table_name', 'numeric_value': 10}
kv=['extract', 'output']
for key, value in my_dict.items():
if isinstance(value, str): # in case value is not a string
kv_string = key + '|' + value
contains = True
for item in kv:
if kv_string.find(item) == -1:
contains = False
if contains:
print(f"{key}: {value}")
else:
print("-w: non-string value in dict")
Related
Is it possible to create a list comprehension for the below for loop?
for key, value in some_dict.items():
if my_value in value:
my_new_var = value['sub_item'].split[0]
This will work :
d={'name':'Yash','age':16}
###############################
keys_values = d.items() # Bonus: Converting the dictionary keys and values to string
d = {str(key): str(value) for key, value in keys_values}#--- ''
#########################
my_value='Yash'
my_new_var = [v for k, v in d.items() if my_value in v] [-1] # edit: now it'll take last value
print(my_new_var)
i managed to do something like this:
out = [value['sub_value'].split[0] for key, value in some_dict.items() for i in value if my_new_var in value]
I have an existing list of Key, Value pairs in my current dictionary called total_list. I want to check my list to see if the length of each Key == 1 in total_list, I want to add that key and its value pair to a new dictionary. This is the code that I've come up with.
total_list = {104370544: [31203.7, 01234], 106813775: [187500.0], 106842625: [60349.8]}
diff_so = defaultdict(list)
for key, val in total_list:
if len(total_list[key]) == 1:
diff_so[key].append[val]
total_list.pop[key]
But I keep getting an error with
"cannot unpack non-iterable int object".
I was wondering if there's anyway for me to fix this code for it to run properly?
Assuming that the OP means a string of one character by length = 1 of the key.
You can do this:
total_list = [{'abc':"1", 'bg':"7", 'a':"7"}]
new_dict = {}
for i in total_list:
for k,v in i.items():
if len(k) == 1:
new_dict[str(k)] = v
else:
pass
print(new_dict)
Output:
{'a': '7'}
After edit:
total_list = {104370544: [31203.7, 1234], 106813775: [187500.0], 106842625: [60349.8]}
new_dict = {}
for k,v in total_list.items():
if len(v) == 1:
new_dict[k] = v
else:
pass
Output:
{'106842625': [60349.8], '106813775': [187500.0]}
You just need a dictionary comprehension
diff_so = {k: v for k, v in total_list.items() if len(v) == 1}
I created two dictionaries. Each is based on a different query of the same database. There is a key and four fields from the database in each dictionary. I want to find all rows of dict_x that are in are in dict_y.
for row in dict_x:
if dict_y.values() not in dict_x.values():
del dict_x[row]
print 'Length dict_x', len(dict_x)
This returns the error
TypeError: 'type' object does not support item deletion
This will work as long as the elements in the array will always be in the same order.
dict_x = {'hi': ['hello', 'hi'], 'bye': ['good bye', 'bye']}
dict_y = {'hi': ['hello', 'hi']}
dict_z = dict()
for key, row in dict_x.items():
if row in dict_y.values():
dict_z[key] = row
print(dict_z)
If the elements won't be in the same order then you'll have to do this:
dict_x = {'hi': ['hi', 'hello'], 'bye': ['good bye', 'bye']}
dict_y = {'hi': ['hello', 'hi']}
dict_z = dict()
for x_key, x_row in dict_x.items():
for y_key, y_row in dict_y.items():
if set(x_row).intersection(y_row):
dict_z[x_key] = y_row
print(dict_z)
>>> dict_a = {'a':[1,1,2,3]}
>>> dict_b = {'b':[1,2]}
>>> for a_key, b_key in zip(dict_a.keys(), dict_b.keys()):
... print [i for i in dict_a[a_key] if i in set(dict_b[b_key])]
...
[1, 1, 2]
The steps to solve the problem would be to
Invert the key value pairs of the dictionaries
Identify the common intersecting keys
Loop through the keys and check if their values match
The code could look something like below
dict_x = {v: k for k, v in dict_x.items()}
dict_y = {v: k for k, v in dict_y.items()}
for key in dict_x.keys() & dict_y.keys():
print(key, dict_x[key])
print(key, dict_y[key])
Here is the dict comprehension equivalent in python 3
result_set = {key: dict_x[key] for key in dict_x.keys() & dict_y.keys() if dict_x[key] == dict_y[key]}
This might help, it will return False if the dict is equal and true if not. I know its other way around
def compare_dict(
dict_1: Dict[Any, Any], dict_2: Dict[Any, Any]
):
new_key = any([False if key in dict_1 else True for key in dict_2])
delete_key = any(
[False if key in dict_2 else True for key in dict_1]
)
if new_key or delete_key:
return True
else:
values_mismatch_flag = any(
[
True if v != dict_1[k] else False
for k, v in dict_2.items()
]
)
if values_mismatch_flag:
return True
return False
I have a dict as below
{"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
and I want to search for a number in this dict and get its respective 'key'
Eg: for 12, i need to return 'low'. slly for 2, return 'high'
You can use a dictionary comprehension for this.
dict = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
key = {k:v for k, v in dict.items() if 12 in v}
Output
In[1]: key.popitem()[0]
Out[1] : 12
This is a job for next.
my_d = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
target = 12
res = next((k for k, v in my_d.items() if target in v), 'N\A')
print(res) # low
Note that if your target value exists in more than one keys, this code will return one of them at random1. If that might by the case and depending on the problem you are working on it may be wiser to get all matching keys instead. To do that, use:
res = [k for k, v in my_d.items() if target in v]
1Actually more like in an uncontrolled fashion.
def getKey(number):
for key, value in d.iteritems():
if number in value:
return key
dict = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
def search_key(val):
for key, value in dict.iteritems():
for i in value:
if i == val:
print "the key is:"+key
return key
#pass any value for which you want to get the key
search_key(9)
I need to write a function which is doing following work
Find a string as value in a dictionary of dictionaries and return its key
(1st key if found in main dictionary, 2nd key if found in sub dictionary).
Source Code
Here is the function which I try to implement, but it works incorrect as I can't find any answer of how to convert list into dictionary as in this case the following error occurs
for v, k in l:
ValueError: need more than 1 value to unpack
def GetKeyFromDictByValue(self, dictionary, value_to_find):
""""""
key_list = [k for (k, v) in dictionary.items() if v == value_to_find]
if key_list.__len__() is not 0:
return key_list[0]
else:
l = [s for s in dictionary.values() if ":" in str(s)]
d = defaultdict(list)
for v, k in l:
d[k].append(v)
print d
dict = {'a': {'a1': 'a2'}, "aa": "aa1", 'aaa': {'aaa1': 'aaa2'}}
print GetKeyFromDictByValue(dict, "a2")
I must do this on Python 2.5
You created a list of only the dictionary values, but then try to loop over it as if it already contains both keys and values of those dictionaries. Perhaps you wanted to loop over each matched dictionary?
l = [v for v in dictionary.values() if ":" in str(v)]
d = defaultdict(list)
for subdict in l:
for k, v in subdict.items():
I'd instead flatten the structure:
def flatten(dictionary):
for key, value in dictionary.iteritems():
if isinstance(value, dict):
# recurse
for res in flatten(value):
yield res
else:
yield key, value
then just search:
def GetKeyFromDictByValue(self, dictionary, value_to_find):
for key, value in flatten(dictionary):
if value == value_to_find:
return key
Demo:
>>> sample = {'a': {'a1': 'a2'}, "aa": "aa1", 'aaa': {'aaa1': 'aaa2'}}
>>> GetKeyFromDictByValue(None, sample, "a2")
'a1'