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}
Related
I am trying to access a specific key in a nest dictionary, then match its value to a string in a list. If the string in the list contains the string in the dictionary value, I want to override the dictionary value with the list value. below is an example.
my_list = ['string1~', 'string2~', 'string3~', 'string4~', 'string5~', 'string6~']
my_iterable = {'A':'xyz',
'B':'string6',
'C':[{'B':'string4', 'D':'123'}],
'E':[{'F':'321', 'B':'string1'}],
'G':'jkl'
}
The key I'm looking for is B, the objective is to override string6 with string6~, string4 with string4~, and so on for all B keys found in the my_iterable.
I have written a function to compute the Levenshtein distance between two strings, but I am struggling to write an efficient ways to override the values of the keys.
def find_and_replace(key, dictionary, original_list):
for k, v in dictionary.items():
if k == key:
#function to check if original_list item contains v
yield v
elif isinstance(v, dict):
for result in find_and_replace(key, v, name_list):
yield result
elif isinstance(v, list):
for d in v:
if isinstance(d, dict):
for result in find_and_replace(key, d, name_list):
yield result
if I call
updated_dict = find_and_replace('B', my_iterable, my_list)
I want updated_dict to return the below:
{'A':'xyz',
'B':'string6~',
'C':[{'B':'string4~', 'D':'123'}],
'E':[{'F':'321', 'B':'string1~'}],
'G':'jkl'
}
Is this the right approach to the most efficient solution, and how can I modify it to return a dictionary with the updated values for B?
You can use below code. I have assumed the structure of input dict to be same throughout the execution.
# Input List
my_list = ['string1~', 'string2~', 'string3~', 'string4~', 'string5~', 'string6~']
# Input Dict
# Removed duplicate key "B" from the dict
my_iterable = {'A':'xyz',
'B':'string6',
'C':[{'B':'string4', 'D':'123'}],
'E':[{'F':'321', 'B':'string1'}],
'G':'jkl',
}
# setting search key
search_key = "B"
# Main code
for i, v in my_iterable.items():
if i == search_key:
if not isinstance(v,list):
search_in_list = [i for i in my_list if v in i]
if search_in_list:
my_iterable[i] = search_in_list[0]
else:
try:
for j, k in v[0].items():
if j == search_key:
search_in_list = [l for l in my_list if k in l]
if search_in_list:
v[0][j] = search_in_list[0]
except:
continue
# print output
print (my_iterable)
# Result -> {'A': 'xyz', 'B': 'string6~', 'C': [{'B': 'string4~', 'D': '123'}], 'E': [{'F': '321', 'B': 'string1~'}], 'G': 'jkl'}
Above can has scope of optimization using list comprehension or using
a function
I hope this helps and counts!
In some cases, if your nesting is kind of complex you can treat the dictionary like a json string and do all sorts of replacements. Its probably not what people would call very pythonic, but gives you a little more flexibility.
import re, json
my_list = ['string1~', 'string2~', 'string3~', 'string4~', 'string5~', 'string6~']
my_iterable = {'A':'xyz',
'B':'string6',
'C':[{'B':'string4', 'D':'123'}],
'E':[{'F':'321', 'B':'string1'}],
'G':'jkl'}
json_str = json.dumps(my_iterable, ensure_ascii=False)
for val in my_list:
json_str = re.sub(re.compile(f"""("[B]":\\W?")({val[:-1]})(")"""), r"\1" + val + r"\3", json_str)
my_iterable = json.loads(json_str)
print(my_iterable)
So what I was trying to do was output the string "33k22k11k", which is just the last value followed by the reversed last key followed by the second last value followed by the second last reversed key and so on. I'm not sure how to get the reversed key value for the specific loop that I am in. From the code I currently I have, I get the output:
dict = {"k1":1, "k2":2, "k3":3}
current=""
current_k=""
for k,v in dict.items():
for i in k:
current_k=i+current_k
current=str(v)+current_k+current
print(current)
print(current_k)
33k2k1k22k1k11k
3k2k1k
Edited
First of all, if you are on python < 3.6, dict does not keep the order of items. You might want to use collections.OrderedDict for your purpose.
d = {"k1":1, "k2":2, "k3":3}
d.keys()
# dict_keys(['k2', 'k1', 'k3'])
whereas,
d = OrderedDict()
d['k1'] = 1
d['k2'] = 2
d['k3'] = 3
d.keys()
# odict_keys(['k1', 'k2', 'k3'])
With our new d, you can either add the key and values and reverse it:
res = ''
for k, v in d.items():
res += str(k) + str(v)
res[::-1]
# '33k22k11k'
or reversely iterate:
res = ''
for k, v in reversed(d.items()):
res += str(v)[::-1] + str(k)[::-1]
res
# '33k22k11k'
I may be wrong but it seems like you would want to reset the value of current_k each time you access a new key
dict = {"k1":1, "k2":2, "k3":3}
current=""
for k,v in dict.items():
current_k=""
for i in k:
current_k=i+current_k
current=str(v)+current_k+current
print(current)
print(current_k)
Why not simply do:
print(''.join([a+str(b) for a,b in dict.items()])[::-1])
Output:
"33k22k11k"
But if the values are different from the keys, do:
print(''.join([str(b)[::-1]+a for a,b in dict.items()[::-1]]))
You can use the Python map function to create the reversed string(using f-string) for each key/value pair and then join it.
dict1 = {"k1":1, "k2":2, "k3":3}
new_dict = "".join(map(lambda k, v: f'{k}{v}'[::-1] , dict1.keys(), dict1.values()))
Output:
33k22k11k
You can do something like this perhaps:
dict = {"k1":1, "k2":2, "k3":3}
print("".join(list(reversed([str(v)+"".join(reversed(k)) for k, v in dict.items()]))))
Output:
33k22k11k
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'
Given a list of dictionaries ( each of which have same keys), I want total number of different values with which a given key is associated
$ li = [{1:2,2:3},{1:2,2:4}] $ the expected output is {1:1,2:2}
I came up with the following piece of code...Is there a better way of doing this ?
counts = {}
values = {}
for i in li:
for key,item in i.items():
try:
if item in values[key]:
continue
except KeyError:
else:
try:
counts[key] += 1
except KeyError:
counts[key] = 1
try:
values[key].append(item)
except KeyError:
values[key] = [item]
Something like this is probably more direct:
from collections import defaultdict
counts = defaultdict(set)
for mydict in li:
for k, v in mydict.items():
counts[k].add(v)
That takes care of the collecting / counting of the values. To display them like you want them, this would get you there:
print dict((k, len(v)) for k, v in counts.items())
# prints {1: 1, 2: 2}
Here is yet another alternative:
from collections import defaultdict
counts = defaultdict(int)
for k, v in set(pair for d in li for pair in d.items()):
counts[k] += 1
And the result:
>>> counts
defaultdict(<type 'int'>, {1: 1, 2: 2})
You could so something like this:
li = [{1:2,2:3},{1:2,2:4}]
def makesets(x, y):
for k, v in x.iteritems():
v.add(y[k])
return x
distinctValues = reduce(makesets, li, dict((k, set()) for k in li[0].keys()))
counts = dict((k, len(v)) for k, v in distinctValues.iteritems())
print counts
When I run this it prints:
{1: 1, 2: 2}
which is the desired result.
counts = {}
values = {}
for i in li:
for key,item in i.items():
if not (key in values.keys()):
values[key] = set()
values[key].add(item)
for key in values.keys():
counts[key] = len(values[key])
using flattening list in case dicts are not alway same length:
li=[{1: 2, 2: 3}, {1: 2, 2: 4}, {1: 3}]
dic={}
for i,j in [item for sublist in li for item in sublist.items()]:
dic[i] = dic[i]+1 if i in dic else 1