every key compares with value(you may say there is spelling check betwen key and value).If there are only 2 words mismatch then print the key
input={"their":"thuor","diksha","dijmno"}
output=["their"]
def find_correct(words_dict):
count=0
final_list=[]
for key,value in words_dict.items():
for i in range(len(value)): # this may need adjusting for different length words
if(value[i]!=key[i]):
count+=1
if(count<=2):
final_list.append(key)
return final_list
print(find_correct({"their":"thuor","diksha":"dijmno"}))
This can be done with list comprehension and sets
print([i for i in d if len(set(i) - set(d[i])) == 2])
Related
I have nested for loops, i think this is making things complicated here.
Here is the dict i have
dict1 = {'1': '##', '2': '##'}
I am looping through this dict and here is the code
for key,value in dict1.items():
###some code ###
if ##condition is true move to next key in the for loop which is '2'##
dict1.next()
I have used dict1.next(). But this is throwing an error "dict' object has no attribute 'next'"
Even tried dict1[key] += 1 and dict1[key] = dict1.setdefault(key, 0) + 1
I understand when skipping to next key in dictionary we have to refer index of key to move on to next item. But no luck with anything and I m not sure using "continue" would fulfil my purpose, because currently I have only one value for each corresponding key ("continue" works if it so), but I want to use this code even if each key had more than one value respectively. Such that "If" condition is true for key 1 and its first corresponding value, the next iteration should be for key 2 and its values respectively.
Sorry for long story
what's wrong with using continue?
dict1 = {'1': [1,4,7], '2': '##'}
for key in dict1.keys():
if key == "1":
continue
else:
print key, dict1[key]
>>> '2 ##'
You can have the nexy key with the following:
keys = dict1.keys()
n = len(keys)
for i in range(n):
thisKey = keys[i]
if some_condition():
nextKey = keys[(i + 1) % n]
nextValue = dict1[nextKey]
print thisKey, nextValue
You have a list of keys, you iterate over the length of the keys.
If your condition is true, you can extract the next key and value.
I have a dictionary like this :
data = {1: [u'-', u's'], 2: [u'je', u'co', u'na'], ...}
The KEY is the LENGTH of the words that belong to it. I want to call a function (that will count levenshtein distance) for words that are longer than X and shorter than Y. How would I do it ?
The main problem is getting the dictionary length because len() returns the number of items in the dictionary, not keys.
Now I am doing it like this:
for k in data:
if k >= len(word)-distance and k <= len(word)+distance:
for item in data[k]:
if levenshtein(word, item) == distance:
words.append(item)
return words
data.keys() will give you the keys, you can iterate over them.
You can get a list of all words with length between X and Y with
sum((words for key, words in data.items() if X<key<Y), [])
I wrote a python function to group a list of words by anagram:
def groupByAnagram(list):
dic = {}
for x in list:
sort = ''.join(sorted(x))
if sort in dic == True:
dic[sort].append(x)
else:
dic[sort] = [x]
for y in dic:
for z in dic[y]:
print z
groupByAnagram(['cat','tac','dog','god','aaa'])
but this only returns:
aaa
god
tac
what am I doing wrong?
if sort in dic == True:
Thanks to operator chaining, this line is equivalent to
if (sort in dic) and (dic == True):
But dic is a dictionary, so it will never compare equal to True. Just drop the == True comparison entirely.
if sort in dic:
remove the "== True" in your if clause. You can just check with sort in dic.
change the if-clause to:
if sort in dic:
and everything works as expected.
You can also remove the if-clause by using the default dict of the collections package. This way you do not have to check if you have to create a new list for your dict, each time.
import collections
def groupByAnagram2(word_list):
dic = collections.defaultdict(list)
for x in word_list:
sort = ''.join(sorted(x))
dic[sort].append(x)
for words in dic.values():
for word in words:
print word
I have a python dictionary containing n key-value pairs, out of which n-1 values are identical and 1 is not. I need to find the key of the distinct element.
For example: consider a python list [{a:1},{b:1},{c:2},{d:1}]. I need the to get 'c' as the output.
I can use a for loop to compare consecutive elements and then use two more for loops to compare those elements with the other elements. But is there a more efficient way to go about it or perhaps a built-in function which I am unaware of?
If you have a dictionary you can quickly check and find the first value which is different from the next two values cycling around the keys of your dictionary.
Here's an example:
def find_different(d):
k = d.keys()
for i in xrange(0, len(k)):
if d[k[i]] != d[k[(i+1)%len(k)]] and d[k[i]] != d[k[(i+2)%len(k)]]:
return k[i]
>>> mydict = {'a':1, 'b':1, 'c':2, 'd':1}
>>> find_different(mydict)
'c'
Otherwise, if what you have is a list of single-key dictionaries, then you can do it quite nicely mapping your list with a function which "extracts" the values from your elements, then check each one using the same logic.
Here's another working example:
def find_different(l):
mask = map(lambda x: x[x.keys()[0]], l)
for i in xrange(0, len(l)):
if mask[i] != mask[(i+1)%len(l)] and mask[i] != mask[(i+2)%len(l)]:
return l[i].keys()[0]
>>> mylist = [{'a':1},{'b':1},{'c':2},{'d':1}]
>>> find_different(mylist)
'c'
NOTE: these solutions do not work in Python 3 as the map function doesn't return a list and neither does the .keys() method of dictionaries.
Assuming that your "list of pairs" (actually list of dictionaries, sigh) cannot be changed:
from collections import defaultdict
def get_pair(d):
return (d.keys()[0], d.values()[0])
def extract_unique(l):
d = defaultdict(list)
for key, value in map(get_pair, l):
d[value].append(key)
return filter(lambda (v,l): len(l) == 1, d.items())[0][1]
If you already have your dictionary, then you make a list of all of the keys: key_list = yourDic.keys(). Using that list, you can then loop through your dictionary. This is easier if you know one of the values, but below I assume that you do not.
yourDic = {'a':1, 'b':4, 'c':1, 'd':1, }
key_list = yourDic.keys()
previous_value = yourDic[key_list[0]] # Making it so loop gets past first test
count = 0
for key in key_list:
test_value = yourDic[key]
if (test_value != previous_value) and count == 1: # Checks first key
print key_list[count - 1]
break
elif (test_value != previous_value):
print key
break
else:
previous_value = test_value
count += 1
So, once you find the value that is different, it will print the key. If you want it to print the value, too, you just need a print test_value statement
I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this
for y in myDict:
print(y+"\t"+myDict[y])
I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok like this
for x in myList:
print(x)
Now I want to remove occurrences of key val pairs in the dictionary where the keys are the list values. I tried this
for x in myList:
for y in myDict:
if x != y: print(y+"\t"+myDict[y])
but on each pass through the list it lets all the others apart from the current `x to the screen
Is there a nice python way to remove the key val pairs from the dictionary if the key exists in the list?
Do you mean
for key in myDict:
if key not in myList:
print(key+"\t"+myDict[key])
Or one of many alternatives:
for key in (set(myDict)-set(myList)):
print(key+"\t"+myDict[key])
mySet = set(myList)
myNewDict = dict(((k, v) for k, v in myDict if k not in mySet))
Note that using mySet instead of myList isn't a concern unless myList has a large number of entries.