I am a newbie in python. I was playing with dictionaries and wanted to know the solution to the given problem
list_ = [['any', 'window', 'says', 'window'], ['dog', 'great'], ['after', 'end', 'explains', 'income', '.', '?']]
dictionary=[('dog', 'cat'), ('window', 'any')]
def replace_matched_items(word_list, dictionary):
int_word = []
int_wordf = []
for lst in word_list:
for ind, item in enumerate(lst):
for key,value in dictionary:
if item in key:
lst[ind] = key
else:
lst[ind] = "NA"
int_word.append(lst)
int_wordf.append(int_word)
return int_wordf
list_ = replace_matched_items(list_, dictionary)
print(list_ )
Output generated is:
[[['NA', 'window', 'NA', 'window'], ['NA', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]
The expected output is:
[[['NA', 'window', 'NA', 'window'], ['dog', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]
I am using python 3
Thanks in advance
Some quick introduction to data structures in python just to clarify your question.
A list is similar to your arrays, where they can be accessed via their index and are mutable meaning items within the list can be changed. Lists are generally identified by brackets [].
For example:
my_array = [4, 8, 16, 32]
print(my_array[0]) # returns 4
print(my_array[3]) # returns 32
my_array[2] = 0
print(my_array) # returns [4, 8, 0, 32]
A tuple is similar to a list, however, the main difference is that they are immutable meaning items within the tuple cannot be changed. Items can still be accessed via their index. They are generally identified by parenthesis ().
For example:
my_tuple = ('this', 'is', 'a', 'tuple', 'of', 'strings')
print(my_tuple[0]) # returns 'this'
my_tuple[1] = 'word' # throws a 'TypeError' as items within tuples cannot be changed.
A dictionary uses a key and value pair to access, store, and change data in a dictionary. Similar to lists, they are mutable, however, each value has their own unique key. To access a value in the dictionary, you have to pass the key within the dictionary. Dictionaries are generally identified by curly braces {}.
For Example:
my_dictionary = {'John':13, 'Bob':31, 'Kelly':24, 'Ryan':17}
print(my_dictionary['Kelly']) # Returns 24
my_dictionary['Kelly'] = 56 # Assigns 56 to Kelly
print(my_dictionary['Kelly']) # Returns 56
The key:value takes this form within the dictionary, and each subsequent key-value pairs are separated by commas.
I would highly suggested reading the official documentation on the Data Structures available for python: Link Here
To answer the question
From your code given, you've used a tuple with your key-value pair encapsulated the tuple in a list as your dictionary data structure.
Your expected output is a result of you iterating through the entire dictionary, and did not handle what will occur once you've found the key for your dictionary. This can be fixed by adding a break statement within your if-statement once a key has been found.
The break statement, will exit your for loop once a key has been found and, will continue onto the next list item.
Your function will end up looking like:
def replace_matched_items(word_list, dictionary):
int_word = []
int_wordf = []
for lst in word_list:
for ind, item in enumerate(lst):
for key,value in dictionary:
if item in key:
lst[ind] = key
break
else:
lst[ind] = "NA"
int_word.append(lst)
int_wordf.append(int_word)
return int_wordf
Suggested to use a Dictionary
Using a Dictionary data structure for your key and value pairs will let you have access to methods that'll let you check whether a key exists inside your dictionary.
If you have a list of keys, and you'd like to check if a dictionary key exists within a list:
this_list = ['any', 'window', 'says', 'window', 'dog',
'great', 'after', 'end', 'explains', 'income', '.', '?']
dictionary = {'dog':'cat', 'window':'any'}
matched_list = []
for keys in dictionary:
if keys in this_list:
matched_list.append(keys) # adds keys that are matched
else:
# do something if the key is in not the dictionary
print(matched_list)
# Returns ['dog', 'window']
Related
I was learning Python and came upon a problem: To convert a list of list to dictionary based on a certain key.
If the input is: [['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]
The output is: {'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}
The logic being, the first element of the inner array is considered as the key for the new dictionary.
I am currently doing it the dirty way by iterating over the entire list. But, is there a better way to do it?
You'll have to iterate over the list. One way is to use dict.setdefault:
out = {}
for k,v in lst:
out.setdefault(k, set()).add(v)
This is the same as the following conditional loop:
out = {}
for k,v in lst:
if k in out:
out[k].add(v)
else:
out[k] = {v}
Output:
{'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}
I'm new to python. I'm trying to find and remove duplicate list values from the dictionary below:
dict = {'happy':['sun', 'moon', 'bills' 'chocolate'], 'sad':['fail', 'test', 'bills', 'baloon'], 'random': ['baloon', 'france', 'sun'] }
I want the dictionary dictionary to look like this after removing the duplicates from the list
expectd_dict = {'happy':['sun', 'moon', 'chocolate', 'bills'], 'sad':['fail', 'test','baloon'], 'random': ['france] }
I have looked for solutions on the internet but to no avail. I have tried creating an empty list and dict, iterating through the dictionary key and value, and also iterating through the list values, then adding it the to the empty list if not present, but I don't seem to be getting the desired result.
output_dict = {}
output_list = []
for key, value in d.items():
if key not in output_dict.values():
for i in value:
if i not in output_list:
output_list.append(i)
output_dict[key] = output_list
print(output_dict)
Think you want process lists in the order 'happy' -> 'random' -> 'sad'.
Loop in the list values, check if it seen in previous action, if not found, add it to the final list, add it to seen_values.
seen_values = set()
for key in ('happy', 'random', 'sad'):
final_list = []
for value in dict[key]:
if value in seen_values:
continue
seen_values.add(value)
final_list.append(value)
dict[key] = final_list
I have a list of dictionaries like this
UNFILTERED LIST OF DICTIONARIES:
[{'team': 'green', 'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice', 'team': 'blue'}, {'team': 'yellow'}]
i need to get FILTERED list with only last appeared key of duplicates like
FILTERED LIST:
[{'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice'}, {'team': 'yellow'}]
** key 'team' will keep only one and the latest value **
(it can be any duplicate key name that i couldn't know in advance so it should be general solution)
thanks a lot for help!
Iterate over the list from last to first dict, save all read keys in a extra list and if a key is already in the extra list delete it from current dict.
I am not so familiar with python but that should work:
myList = [{'team': 'green', 'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice', 'team': 'blue'}, {'team': 'yellow'}]
myList.reverse()
delList = []
for dict in myList:
for key in list(dict.keys()):
if key in delList:
del dict[key]
else:
delList.append(key)
myList.reverse()
print(myList)
I have a dictionary similar to this:
table_wood = {'Red': {'Abbreviation': 'R',
'Instances': 269601,
'Code': '8924',
'Discovered': '1876-08-01',
'Largest usage': 'Douglas',
'Indigo': {'Abbreviation': 'IN',
'Instances': 216443,
'Code': '2343',
'Discovered': '1890-07-03',
'Largest usage': 'Freida'}}
I need to iterate through the table_wood dictionary and calculate (instances/code) for each dictionary in table_wood. After I do this I need to report which has the greatest number of instances and which has the lowest.
I have tried using for loops to append the pertinent values to empty lists and then using a nested for loop to compare these list values to see which of the original instances is greatest and lowest.
It involves a great number of empty lists, and I know that there is a better way if I can just store them as new key/value pairs in an empty dictionary.
instanceCodeRate = []
colorInstances = []
highestInstance = []
lowestInstance = []
for color in table_wood:
colorRate.append(color+ ": " +str(round((table_wood[color]["Instances"])/(table_wood[color]["Code"]),2))+ " instances per code.\n")
#print(instanceCodeRate)
colorInstances.append(table_wood[color]["Instances"])
#print(colorInstances)
for instance in colorInstances:
if ((table_wood[color]["Instances"]) == min(colorInstances)):
lowestInstance.append(color)
elif ((table_wood[color]["Instances"]) == max(colorInstances)):
highestInstance.append(color)
#print(instanceCodeRate)
#print(highestInstance)
#print(lowestInstance)
When I print(instanceCodeRate) it does it as list elements, which invalidates the "\n" whitespace character I'm trying to print so that each entry has its own line.
My elif works by only storing the largest, but for some reason the if statement which stores the minimum stores multiple list elements where there should only be one.
Python's max function takes in an optional key argument
colors = list(table_wood.keys())
attrs = list(table_wood.values())
max_value = max(attrs, key=lambda: x: x['Instances']/int(x['Code']))
this prints out:
{'Abbreviation': 'IN',
'Instances': 216443,
'Code': '2343',
'Discovered': '1890-07-03',
'Largest usage': 'Freida'}
This same can be done with min
I have the following:
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
How can I iterate through the dictionary and append one of those values into that list? What if I only want to append the value of 'key2'.
If you only want to append a specific set of values you don't need to iterate through the dictionary can simply add it to the list
list_of_values.append(x["key2"])
However, if you insist on iterating through the dictionary you can iterate through the key value pairs:
for key, value in x.items():
if key == "key2":
list_of_values.append(value)
If you really want to iterate over the dictionary I would suggest using list comprehensions and thereby creating a new list and inserting 'key2' :
list_of_values = [x[key] for key in x if key == 'key2']
because that can be easily extended to search for multiple keywords:
keys_to_add = ['key2'] # Add the other keys to that list.
list_of_values = [x[key] for key in x if key in keys_to_add]
That has the simple advantage that you create your result in one step and don't need to append multiple times. After you are finished iterating over the dictionary you can append the list, just to make it interesting, you can do it without append by just adding the new list to the older one:
list_of_values += [x[key] for key in x if key in keys_to_add]
Notice how I add them in-place with += which is exactly equivalent to calling list_of_values.append(...).
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
list_of_values.append(x['key2'])