Python3 - Combine Dictionaries with existing key value pairs - python-3.x

So... I know we can combine 2 dictionaries from python 3.5 like so:
z = {**x,**y} # x,y are 2 similar dictionaries, with nested entries
But in this method, any conflicting key,value pairs in 'x' is replaced with the ones in 'y'.
I want the conflicting key,value pairs to contain largest data present in x or y.
For example:
x = {1:'small_data',2:{1:'random laaaarge data',2:'random small data'}}
y = {1:'laaaaaarge_data',2:{1:'random small data',2:'random laaaarge data'}}
Now
z = {**x,**y}
# DATA in z should be {1:'laaaaaarge_data',2:{1:'random laaaarge data',2:'random laaaarge data'}}
NOTE: It should work for any arbitrary data that has a size.
Is this even possible? If so, what is the most pythonic way to do it.

Why not something like:
def merge_dicts(dict_list):
merged = {}
for sub_dict in dict_list:
for key, value in sub_dict.items():
if key in merged:
merged[key] = get_biggest(merged[key], value)
else:
merged[key] = value
return merged
def get_biggest(*items):
# function for comparing your 2 items based on your "size" requirements
return biggest

Related

Python losing track of index location in for loop when my list has duplicate values

I'm trying to iterate over pairs of integers in a list. I'd like to return pairs where the sum equals some variable value.
This seems to be working just fine when the list of integers doesn't have repeat numbers. However, once I add repeat numbers to the list the loop seems to be getting confused about where it is. I'm guessing this based on my statements:
print(list.index(item))
print(list.index(item2))
Here is my code:
working_list = [1,2,3,4,5]
broken_list = [1,3,3,4,5]
def find_pairs(list, k):
pairs_list = []
for item in list:
for item2 in list:
print(list.index(item))
print(list.index(item2))
if list.index(item) < list.index(item2):
sum = item + item2;
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
### First parameter is the name is the list to check.
### Second parameter is the integer you're looking for each pair to sum to.
find_pairs(broken_list, 6)
working_list is fine. When I run broken_list looking for pairs which sum to 6, I'm getting back (1,5) but I should also get back (3,3) and I'm not.
You are trying to use list.index(item) < list.index(item2) to ensure that you do not double count the pairs. However, broken_list.index(3) returns 1 for both the first and second 3 in the list. I.e. the return value is not the actual index you want (unless the list only contains unique elements, like working_list). To get the actual index, use enumerate. The simplest implementation would be
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for j, item2 in enumerate(list):
if i < j:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
For small lists this is fine, but we could be more efficient by only looping over the elements we want using slicing, hence eliminating the if statement:
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for item2 in list[i+1:]:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
Note on variable names
Finally, I have to comment on your choice of variable names: list and sum are already defined by Python, and so it's bad style to use these as variable names. Furthermore, 'items' are commonly used to refer to a key-value pair of objects, and so I would refrain from using this name for a single value as well (I guess something like 'element' is more suitable).

Nesting dictionaries with a for loop

I am trying to add a dictionary within a dictionary in the current code like this!
i = 0
A ={}
x = [...]
for i in x:
(a,b) = func(x)#this returns two different Dictionaries as a and b
for key in a.keys():
A[key] = {}
A[key][i] = a[key]
print('A:',A)
as I executed it, I am getting 'A' dictionary being printed throughout the loop! But, i need them in one single dictionary say: "C"
How do I do that?

Sort a dictionary based on alphanumeric keys

I have a dictionary that has alphanumeric keys and I need to sort them based on increasing order of numeric value of the key.Below is my dictionary
output_filters = {"filter22": "red", "filter13": "green", "filter36": "yellow"}
I want the final dictionary to be sorted like below
output_filters = {"filter13": "green", "filter22": "red", "filter36": "yellow"}
Now I know there are similar stackoverflow questions out there but I am not able to adapt it to my situation.
This is what I have done so far, but it doesn't work
def key_func(s):
return [int(x) if x.isdigit() else x for x in re.findall(r'\D+|\d+', s)]
sorted_keys = sorted(output_filters, key=key_func)
It gives inaccurate result.How can this be done?
The following will give you a sorted List of keys.
x = [k for k, v in output_filters.items()]
x = sorted(x, key=lambda x: int(x[6:])) # this will remove "filter" prefix
# ['filter13', 'filter22', 'filter36']
However, you can't sort a dictionary. They are unordered. If you really need it to be sorted, then you will need to use OrderedDict. It is an official built-in module that comes with python itself.
https://docs.python.org/2/library/collections.html#collections.OrderedDict

Python 3.X: Implement returnGreater() function using a list of integers and a value

The function must return a list consisting of the numbers greater than the second number in the function
It must be able to do the following when functioning:
returnGreater([1,2,3,4,5], 3)
[4,5]
returnGreater([-8,2,-4,1,3,-5],3)
[]
Here's what I have (I've gone through a few iterations), though I get a Type Error for trying to use a ">" symbol between an int and list:
def returnGreater (x,y):
"x:list(int) , return:list(int)"
#greater: int
greater = []
for y in x:
#x: int
if x > y:
x = greater
return greater
You're using the name y for two different things in your code. It's both an argument (the number to compare against) and the loop variable. You should use a different name for one of those.
I'd strongly suggest picking meaningful names, as that will make it much clearer what each variable means, as well as making it much less likely you'll use the same name for two different things. For instance, here's how I'd name the variables (getting rid of both x and y):
def returnGreater(list_of_numbers, threshold):
greater = []
for item in list_of_numbers:
if item > threshold:
greater.append(item)
return greater
You had another issue with the line x = greater, which didn't do anything useful (it replaced the reference to the original list with a reference to the empty greater list. You should be appending the item you just compared to the greater list instead.
I recommend filter. Easy and Graceful way.
def returnGreater(x, y):
return list(filter(lambda a:a>y, x))
It means, filter each element a in list x using lambda whether a is greater than y or not.
List Comprehensions
def returnGreater(_list, value):
return [x for x in _list if x > value]

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources