python parse string and turn into dictionary input - python

this is my list:
list1 = ('/a/b/c/Hello1/d/e','/a/b/c/Hello2/d/e','/a/b/c/Hello3/d/e')
list2 = []
for x in list1:
y = x.split('/')[4]
list2.append(y)
list2 = ['Hello1', 'Hello2', 'Hello3']
Now I want to create a dictionary where Hello[1-3] is my key and the corresponding string '/a/b/c/Hello[1-3]/d/e' is the value.
How can I connect key and value in python. I am sure this is fairly easy, but I don't know.
Thank you.

You can use a dict comprehension to achieve this.
>>> {s.split('/')[4] : s for s in list1}
{'Hello2': '/a/b/c/Hello2/d/e',
'Hello3': '/a/b/c/Hello3/d/e',
'Hello1': '/a/b/c/Hello1/d/e'}

Assuming that you have the same number of elements in list1 and list2:
dict(zip(list2, list1))

Related

concentrate 2 lists in python based on a shared substring

I have two lists, for example they look something like this:
list1 = ["Time1Person001", "Time1Person002", "Time1Person003", "Time1Person004", "Time1Person005"]
list2 = ["Time2Person001", "Time2Person003", "Time2Person004", "Time2Person007"]
I want to create a third list that contains only strings that share a substring of the last 3 charachters, so the output should be:
list3 = ["Time1Person001", "Time1Person003", "Time1Person004", "Time2Person001", "Time2Person003", "Time2Person004"]
Efficient way to do it?
Thanks!
Create a set of the common endings then filter each list by that set.
list1 = ["Time1Person001", "Time1Person002", "Time1Person003", "Time1Person004", "Time1Person005"]
list2 = ["Time2Person001", "Time2Person003", "Time2Person004", "Time2Person007"]
endings = set(v[-3:] for v in list1) & set(v[-3:] for v in list2)
list3 = [v for v in list1+list2 if v[-3:] in endings]
Is this what you're after:
list3 = [x for x in list1 for y in list2 if x[-3:] == y[-3:]]

sort string list by another string list python

5 downvotes for what? like seriously wtf?
I asked a clear question and got a clear answer from Barmer.
Now i cant ask another question and now im forced to create a new stack overflow account and dont suggest that i dont cause your system is shit so yes i 100% absolutely will create a new one. and another one, and another one.
Eat shit.
So i have 2 lists.
list1 is the list of which order im trying to recreate.
list2 is the unordered list.
How to arrange list2 in same order as list1?
List1
list1 = [
"loaded_sound,sfx/weapon/smg/type100/fire",
"loaded_sound,sfx/weapon/smg/type100/foley",
"loaded_sound,sfx/weapon/special/bouncing_betty",
"loaded_sound,sfx/weapon/special/flame_thrower/foley",
"loaded_sound,sfx/weapon/special/molotov",
"loaded_sound,sfx/weapon/special/ptrs/fire",
"loaded_sound,sfx/weapon/special/satchel_charge",
"loaded_sound,sfx/weapon/tank/kingtiger/fire",
"loaded_sound,sfx/weapon/tank/ringoffs",
"loaded_sound,sfx/weapon/tank/sherman/fire",
"loaded_sound,sfx/weapon/tank/tank_reload/foley",
"loaded_sound,sfx/weapon/tank/tank_reload",
"loaded_sound,sfx/weapon/tesla/bounce",
"loaded_sound,sfx/weapon/tesla",
"loaded_sound,sfx/weapon/uber",
"loaded_sound,stream/music/mission/zombie",
"loaded_sound,voiceovers/zombie/ann",
"loaded_sound,voiceovers/zombie/monkey/explo_vox",
"loaded_sound,voiceovers/zombie/monkey/groan",
"loaded_sound,voiceovers/zombie/monkey",
"loaded_sound,voiceovers/zombie/monkey/raise_vox",
"loaded_sound,voiceovers/zombie/pa"
]
List2:
list2 = [
"loaded_sound,sfx/weapon/smg/type100/fire",
"loaded_sound,voiceovers/zombie/pa",
"loaded_sound,sfx/weapon/smg/type100/foley",
"loaded_sound,voiceovers/zombie/monkey/raise_vox",
"loaded_sound,sfx/weapon/special/bouncing_betty",
"loaded_sound,sfx/weapon/special/flame_thrower/foley",
"loaded_sound,voiceovers/zombie/monkey",
"loaded_sound,voiceovers/zombie/monkey/groan",
"loaded_sound,sfx/weapon/special/molotov",
"loaded_sound,voiceovers/zombie/monkey/explo_vox",
"loaded_sound,sfx/weapon/special/ptrs/fire",
"loaded_sound,voiceovers/zombie/ann",
"loaded_sound,sfx/weapon/special/satchel_charge",
"loaded_sound,stream/music/mission/zombie",
"loaded_sound,sfx/weapon/tank/kingtiger/fire",
"loaded_sound,sfx/weapon/uber",
"loaded_sound,sfx/weapon/tank/ringoffs",
"loaded_sound,sfx/weapon/tesla",
"loaded_sound,sfx/weapon/tank/sherman/fire",
"loaded_sound,sfx/weapon/tesla/bounce",
"loaded_sound,sfx/weapon/tank/tank_reload/foley",
"loaded_sound,sfx/weapon/tank/tank_reload",
]
What ive tried:
_newList = []
# sort list2 in same order as list 1
for i in list1:
_line_ = i
for j in list2:
if j == _line_:
_newList.append(j)
But all this did was recreate list2 as it is. it didnt rearrange anything.
You can use the index in list1 as the key when sorting list2.
If the lists are long, it would be good to create a dictionary that returns the indexes, rather than searching for each.
list1_dict = {val: i for i, val in enumerate(list1)}
list2.sort(key = lambda x: list1_dict.get(x, -1))
If there are any elements in list2 that aren't in list1, this will sort them to the beginning.
I suggest you the following one-line style code:
list2 = [i for i in list1 if i in list2]

Easier way to check if an item from one list of tuples doesn't exist in another list of tuples in python

I have two lists of tuples, say,
list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
Expected output: 'item4' # Item that doesn't exist in list2
As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?
Assuming your tuple structure is exactly as shown above, this would work:
tuple(set(x[0] for x in list1) - set(x[0] for x in list2))
or per #don't talk just code, better as set comprehensions:
tuple({x[0] for x in list1} - {x[0] for x in list2})
result:
('item4',)
This gives you {'item4'}:
next(zip(*list1)) - dict(list2).keys()
The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').
The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.
Try it online!
This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.
list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []
OutputTuple = [(a) for a, b in list2]
for i in list1:
if i in OutputTuple:
pass
else:
not_in_tuple.append(i)
for i in not_in_tuple:
print(i)
You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:
items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))
Output:
>>> list3
[('item4',)]
Try set.difference:
>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>>
Or even better:
>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>>
that is a difference operation for sets:
set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)
output:
{'item4'}
for i in list1:
a=i[0]
for j in list2:
b=j[0]
if a==b:
break
else:
print(a)

How to delete a dictionary from a list based on values from another dictionary in a list?

I've spent about 6 hours on this, so I feel justified in asking a question. :)
My problem
list1 = [
{extension: 1000, id: 1}
{extension: 1001, id: 1}
{extension: 1000, id: 2}
]
list2 = [
{Stationextension: 1000, id: 1, name: bob}
{Stationextension: 1001, id: 1, name: sal}
{Stationextension: 1000, id: 2, name: cindy}
]
My pseudo code is this.
Delete list2[d] (whole dictionary from list of dicts) where list1[d]['extension'] == list2[d]['Stationextension'] AND id == id.
List 1 is much smaller and has to stay unchanged relative to list 2 if that matters.
Using Python3.3, I have something like
[x for x in list2 if (list1[x]['stationExtension'] == x.get('extension'))]
Thanks !
list2 = [x for x in list2 if {'extension': x['Stationextension'], 'id': x['id']} not in list1]
or, if you know that the lengths and indexes will match:
list2 = [y for x,y in itertools.izip(list1, list2) if x['extension'] == y['StationExtension'] and x['id'] == y['id']]
The right way to do this is to use the right data structures for the job. Instead of figuring out how to search a list based on a key, use a dict with that key. For example:
dict1 = {x['extension']: x for x in list1}
Now, you can just write this:
[x for x in list2 if x['stationExtension'] in dict1}
Elsewhere in your question, it seems like you wanted to use the extension and the id, not just the extension, as a key. But that's just as easy; you can use a tuple:
dict1 = {(x['extension'], x['id']): x for x in list1}
[x for x in list2 if (x['stationExtension'], x['id']) in dict1}
If you want to know why your code doesn't work… let's look at it:
[x for x in list2 if (list1[x]['stationExtension'] == x.get('extension'))]
list1[x] is trying to use the dict as an index, which doesn't mean anything. What you really want to say is "if, for any element of list1, element['stationExtension'] == x.get('extension')". And you can translate that almost directly to Python:
[x for x in list2
if any(element['stationExtension'] == x.get('extension')
for element in list1)]
And of course to add the and element['id'] == x['id'] onto the end of the condition.
But again, the dict is a better solution. Besides being a whole lot simpler to read and write, it's also more efficient. Searching for any matches in a list requires checking each element in the list; searching for any matches in a dict just requires hashing the key and looking it up in a hash table. So, this way takes O(NM) time (where N is the length of list1, and M is the length of list2), while the dict only takes O(M) time.
Assuming that you want to delete items from list2 with the same value in "Stationextention" on list2 and "extention" on list 1 -
You better first create a set with all values to delete - that will avoid a linear search at each time you want to check if an entry will stay:
indexes = set(item["extention"] for item in list1)
And - one thing that happens is that you usually can't iterate over a list and delete items from it while at it:
new_list2 = []
for item in list2:
if item["Stationextention"] not in indexes:
new_list2.append(item)
list2 = new_list2
Python 2.7:
removelist=[]
for i,x in enumerate(list2):
if x['Stationextension'] == list1[i]['extension'] and x['id'] == list1[i]['id']:
removelist+=[i]
And once you've decided what to delete:
for x in removelist:
del list1[x]

Python append adds an item to every variable

I'm iterating on a list and attempting to create sublists from its items. Every time I append to a variable, the value is added to every other variable that I have defined. I've stripped down the code substantially to illustrate.
item = 'things.separated.by.periods'.split('.')
list1 = list2 = []
i = item.pop(0)
print i
list1.append(i)
i = item.pop(0)
print i
list2.append(i)
print(item, list1, list2)
Returns:
things
separated
(['by', 'periods'], ['things', 'separated'], ['things', 'separated'])
What I expected:
things
separated
(['by', 'periods'], ['things'], ['separated'])
I think this might by answered here, but I'm not sure how to apply this fix to my circumstances. Thanks in advance!
The problem is the line
list1 = list2 = []
This makes list1 and list2 refer to the exact same list, so that if you append an item to one you also append it to the other. Change it to
list1 = []
list2 = []
list1 = list2 = []
You are setting list1 to be the exact same list as list2. Therefore, they basically mean the same thing.
To fix this, try something like this:
list1, list2 = [], []

Categories