How to sort one string using another string - python

I have one string of letters that are ordered as follows:
List1 = 'ZQXJKVBPYGFWMUCLDRHSNIOATE'
I have another string which is a bunch of characters
List2 = 'AVERT'
I want to order List2 based on List1. eg. List2 should get ordered as,
VRATE
How would I do this in python?

You can use sorted with the following key:
List1 = 'ZQXJKVBPYGFWMUCLDRHSNIOATE'
List2 = 'AVERT'
''.join(sorted(List2, key=List1.index))
# 'VRATE'
Or, for a better performance you could define a dictionary from List1 using enumerate, consisting on (value, index) and sort by looking up each value in List2:
d = {j:i for i, j in enumerate(List1)}
# {'Z': 0, 'Q': 1, 'X': 2, 'J': 3, 'K': 4, ...
''.join(sorted(List2, key = lambda x: d[x]))
# 'VRATE'

This will work:
List1 = 'ZQXJKVBPYGFWMUCLDRHSNIOATE'
List2 = 'AVERT'
List3 = ''
for i in List1:
if i in List2:
List3+=i
print(List3)

Related

how can I merge lists to create a python dictionary

So I have tried many methods to do this but could not find a working solution. In this problem, I have two python arrays and I would like to join them to create a big dictionary. It would go something like this:
`list1 = [
[2, "ford"],
[4,"Ferrari"],
[3, "Mercedes"],
[1, "BMW"]
]`
`list2 = [
[4, "mustang"],
[3,"LaFerrari"],
[2,"CLA"],
[1,"M5"],
[6,"opel"]
]`
The result that I would like to have is a dictionary that looks like this:
`result = {
1: ["BMW","M5"], 2: ["Ford","CLA"], 3: ["Mercedes","LaFerrari"], 4: ["Ferrari","Mustang"], 6:["Opel"]
}`
So it just basically needs to merge these two arrays based on the "key" (which is just the [0] place in the array)
It looks like task for collections.defaultdict I would do:
import collections
list1 = [
[1, "ford"],
[2,"Ferrari"],
[3, "Mercedes"],
[4, "BMW"]
]
list2 = [
[1, "mustang"],
[2,"LaFerrari"],
[3,"CLA"],
[4,"M5"]
]
result = collections.defaultdict(list)
for key, value in list1:
result[key].append(value)
for key, value in list2:
result[key].append(value)
result = dict(result)
print(result)
Output:
{1: ['ford', 'mustang'], 2: ['Ferrari', 'LaFerrari'], 3: ['Mercedes', 'CLA'], 4: ['BMW', 'M5']}
Here I used defaultdict with lists, unlike common dict if you try do something with value under key which do not exist yet, it did place list() i.e. empty list, then do requested action (appending in this case). At end I convert it into dict just to fullfill your requirement (create a python dictionary).
Use collections.defaultdict
from collections import defaultdict
result = defaultdict(list)
for k,v in list1 + list2:
result[k].append(v)
print (dict(result))
#{2: ['ford', 'CLA'], 4: ['Ferrari', 'mustang'], 3: ['Mercedes', 'LaFerrari'], 1: ['BMW', 'M5'], 6: ['opel']}
I am also pretty new to Python, but I think something like this should work if both lists have the same keys:
list1 = [
[1, "ford"],
[2, "Ferrari"],
[3, "Mercedes"],
[4, "BMW"]
]
list2 = [
[1, "mustang"],
[2, "LaFerrari"],
[3, "CLA"],
[4, "M5"]
]
dict1 = dict(list1)
dict2 = dict(list2)
result = {}
for key,val in dict1.items():
result[key] = [val]
for key, val in dict2.items():
result[key].append(val)
print(result)
output
{1: ['ford', 'mustang'], 2: ['Ferrari', 'LaFerrari'], 3: ['Mercedes', 'CLA'], 4: ['BMW', 'M5']}
As already mentioned, I am a newbie too, so there is probably a more "pythonic" way of doing this.
First, create a dict using the values in list1. Then update the lists in the dict with the values from list2, or create new lists for the keys in list2 which don't exist in list1:
result = {i: [j] for i, j in list1} # create initial dict from all values in list1
for i, j in list2:
if i in result:
result[i].append(j) # add to preexisting list corresponding to key
else:
result[i] = [j] # create new list corresponding to key
If your lists will have multiple values, you can use this where you handle the add logic in a separate function:
result = {}
def add_to_dict(d, key, val):
if key in d:
d[key].append(val)
else:
d[key] = [val]
for el in (list1 + list2):
key, *vals = el
for val in vals:
add_to_dict(result, key, val)
Here, rather than assuming each sublist has only 2 elements, we can unpack the key as the first element and the rest of the elements into a list called vals. Then, we can iterate over the list and perform the same adding logic
If you're sure that both lists contain the same number of items and both has a matching first element in each item (1, 2, 3, 4 in your example),
result = {k: [dict(list1)[k], dict(list2)[k]] for k in dict(list1)}

Python: sort elements of first list by elements of second list

dict = {“Liz”: 4, “Garry”: 4, “Barry”:6}
list1 = []
for m in sorted(result_dict, key=result_dict.get, reverse=True):
list1.append(m)
After that we have two lists:
list1 = ["Barry","Liz", "Garry"]
list2 = [“Garry”, “Liz”, “Barry”]
I want that output be like - if elements had same value in dict, in list1 they should be in order of list2 -> for example, if Garry was first in list2, in list1 he too sould be first after "Barry":
list1 = ["Barry", "Garry", "Liz"]
The key function can return a tuple to break ties. So in your case
d = {"Liz": 4, "Garry": 4, "Barry": 6}
list2 = ["Garry", "Liz", "Barry"]
list1 = sorted(d, key=lambda x: (d.get(x), -list2.index(x)), reverse=True)
print(list1)
will print
['Barry', 'Garry', 'Liz']
You need to use as a key the combination of your current key with the positions on the second list, something like this:
dict = {'Liz': 4, 'Garry': 4, 'Barry': 6}
list2 = ['Garry', 'Liz', 'Barry']
dict2 = {key: i for i, key in enumerate(list2)}
list1 = sorted(dict, key=lambda x: (dict.get(x), -1*dict2.get(x)), reverse=True)
print(list1)
Output
['Barry', 'Garry', 'Liz']
This approach is faster for large list than using list.index. In fact calling index will make the complexity of the algorithm O(n*2) therefore hindering the expected complexity of the sorting algorithm which is O(n*logn) using a dictionary will keep it the same.

How to find intersection of two list of dictionaries in Python 3?

i've found similar, almost same questions but none of these helped me.
For example, if i have two lists:
list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}]
list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}]
You can see that in first list all dicts have same 'a' and in second the key 'b' is same in all dicts in list. I want to find a dictionary which has the key 'a' from first list and key 'b' from second list but only if that dictionary is inside one of these lists (in this example, it would be [{'a':1, 'b':4, 'c':139}]). Thanks a lot in advance :)
Not particularly attractive, but does the trick.
list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}]
list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}]
newdict = {} #the dictionary with appropriate 'a' and 'b' values that you will then search for
#get 'a' value
if list1[0]['a']==list1[1]['a']:
newdict['a'] = list1[0]['a']
#get 'b' value
if list2[0]['b']==list2[1]['b']:
newdict['b'] = list2[0]['b']
#just in case 'a' and 'b' are not in list1 and list2, respectively
if len(newdict)!=2:
return
#find if a dictionary that matches newdict in list1 or list2, if it exists
for dict in list1+list2:
matches = True #assume the dictionaries 'a' and 'b' values match
for item in newdict: #run through 'a' and 'b'
if item not in dict:
matches = False
else:
if dict[item]!=newdict[item]:
matches = False
if matches:
print(dict)
return
This solution works with any keys:
def key_same_in_all_dict(dict_list):
same_value = None
same_value_key = None
for key, value in dict_list[0].items():
if all(d[key] == value for d in dict_list):
same_value = value
same_value_key = key
break
return same_value, same_value_key
list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}]
list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}]
list1value, list1key = key_same_in_all_dict(list1)
list2value, list2key = key_same_in_all_dict(list2)
for dictionary in list1 + list2:
if list1key in dictionary and dictionary[list1key] == list1value and list2key in dictionary and dictionary[list2key] == list2value:
print(dictionary)
Prints {'a': 1, 'b': 4, 'c': 139}
This maybe:
your_a = list1[0]['a'] # will give 1
your_b = list2[0]['b'] # will give 4
answer = next((x for x in list1 + list2 if x['a'] == your_a and x['b'] == your_b), None)

Dictionary comprehension to build list of lists: referencing the current value for a key during comprehension

I am trying to create a list of lists based on hashes. That is, I want a list of lists of items that hash the same. Is this possible in a single-line comprehension?
Here is the simple code that works without comprehensions:
def list_of_lists(items):
items_by_hash = defaultdict(list)
for item in items:
words_by_key[hash(item)].append(item)
return words_by_key.values()
For example, let's say we have this simple hash function:
def hash(string):
import __builtin__
return __builtin__.hash(string) % 10
Then,
>>> l = ['sam', 'nick', 'nathan', 'mike']
>>> [hash(x) for x in l]
[4, 3, 2, 2]
>>>
>>> list_of_lists(l)
[['nathan', 'mike'], ['nick'], ['sam']]
Is there any way I could do this in a comprehension? I need to be able to reference the dictionary I'm building mid-comprehension, in order to append the next item to the list-value.
This is the best I've got, but it doesn't work:
>>> { hash(word) : [word] for word in l }.values()
[['mike'], ['nick'], ['sam']]
It obviously creates a new list every time which is not what I want. I want something like
{ hash(word) : __this__[hash(word)] + [word] for word in l }.values()
or
>>> dict([ (hash(word), word) for word in l ])
{2: 'mike', 3: 'nick', 4: 'sam'}
but this causes the same problem.
[[y[1] for y in x[1]] for x in itertools.groupby(sorted((hash(y), y)
for y in items), operator.itemgetter(0))]

how to sort a dictionary val along with the key in python

I have two dictionary, and I need to sort one of the dictionary along with key and value. As sorting is not provided for dictionary, how can i achieve this?
considering a dictionary which i wan to sort will be:
list1 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768]
list2 = [0,1,2,3,4,5]
dic = {'val': list1, 'key': list2}
So, when i sort it, it should display like :
>>> dic
{'key': [2,4,5,0,1,3], 'val':[0.7654,2.1222, 7.8768,10.0035,12.3243,15.2487]}
Thanks in advance!
Zip the values together, sort, and unzip:
dic['val'], dic['key'] = zip(*sorted(zip(dic['val'], dic['key'])))
Demo:
>>> list1 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768]
>>> list2 = [0,1,2,3,4,5]
>>> dic = {'val': list1, 'key': list2}
>>> dic['val'], dic['key'] = zip(*sorted(zip(dic['val'], dic['key'])))
>>> dic
{'key': (2, 4, 5, 0, 1, 3), 'val': (0.7654, 2.1222, 7.8768, 10.0035, 12.3243, 15.2487)}
The fact that the two lists happen to be values in a dictionary doesn't prevent them from being sorted.
You can sort them before even creating the dict and then create the dict
list1, list2 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768], [0,1,2,3,4,5]
key, val = zip(*sorted(zip(list1, list2)))
print dict(key=key, val=val)
# {'val': (2,4,5,0,1,3), 'key': (0.7654,2.1222,7.8768,10.0035,12.3243,15.2487)}

Categories