Python Iterating through List of List - python-3.x

Heres my code
stockList = [
['AMD', '57.00', '56.23', '58.40', '56.51'],
['AMZN', '3,138.29', '3,111.03', '3242.56689', '3,126.58'],
['ATVI', '80.76', '79.16', '81.86', '79.55'],
['BA', '178.63', '168.86', '176.96', '169.70'],
['BAC', '24.42', '23.43', '23.95', '23.54'],
['DAL', '26.43', '25.53', '26.87', '25.66'],
['FB', '241.75', '240.00', '248.06', '241.20'],
['GE', '7.04', '6.76', '6.95', '6.79'],
['GOOGL', '1,555.92', '1,536.36', '1,576.03', '1,544.04'],
['GPS', '12.77', '12.04', '12.72', '12.10'],
['GRUB', '70.96', '69.71', '70.65', '70.06'],
['HD', '262.42', '258.72', '261.81', '260.01'],
['LUV', '33.62', '32.45', '33.53', '32.61'],
['MSFT', '208.75', '206.72', '213.58', '207.76'],
['MU', '51.52', '50.49', '52.31', '50.74'],
['NFLX', '490.10', '492.26', '511.52', '494.72', 'SUCCESS'],
['PCG', '9.49', '8.96', '9.52', '9.01'],
['PFE', '36.69', '35.87', '37.02', '36.05'],
['QQQ', '264.00', '263.27', '267.11', '264.58', 'SUCCESS'],
['ROKU', '153.36', '148.37', '153.70', '149.11'],
['SHOP', '952.83', '976.45', '1,036.25', '981.33', 'SUCCESS'],
['SPY', '325.01', '323.64', '325.47', '325.25', 'SUCCESS'],
['SQ', '126.99', '125.13', '130.80', '125.76'],
['T', '30.25', '29.58', '30.07', '29.73'],
['TSLA', '1,568.36', '1,646.56', '1,712.58', '1,654.79', 'SUCCESS'],
['TTWO', '153.06', '152.45', '154.47', '153.22', 'SUCCESS'],
['TWTR', '37.01', '36.03246', '36.7210083', '36.21'],
['WFC', '26.20', '24.45272', '25.0438213', '24.57'],
['WMT', '132.33', '130.8515', '132.522049', '131.51']
]
keyword = 'SUCCESS'
secondList = []
for item in stockList:
if item[4] == keyword:
secondList.append(stockList[0])
print(secondList)
My use case is, to go through this lists of list, find which list contains the keyword, from there send the first item in the list. I am able to get it with one single list, however I can't do it with a list of list.
On top of that, how would I go through a dictionary containing lists?
{
'majorDimension': 'ROWS',
'range': 'Sheet1!A2:F30',
'values': [
['AMD', '57.00', '56.23', '58.40', '56.51'],
['AMZN', '3,138.29', '3,111.03', '3242.56689', '3,126.58'],
['ATVI', '80.76', '79.16', '81.86', '79.55'],
['BA', '178.63', '168.86', '176.96', '169.70'],
['BAC', '24.42', '23.43', '23.95', '23.54'],
['DAL', '26.43', '25.53', '26.87', '25.66'],
['FB', '241.75', '240.00', '248.06', '241.20'],
['GE', '7.04', '6.76', '6.95', '6.79'],
['GOOGL', '1,555.92', '1,536.36', '1,576.03', '1,544.04'],
['GPS', '12.77', '12.04', '12.72', '12.10'],
['GRUB', '70.96', '69.71', '70.65', '70.06'],
['HD', '262.42', '258.72', '261.81', '260.01'],
['LUV', '33.62', '32.45', '33.53', '32.61'],
['MSFT', '208.75', '206.72', '213.58', '207.76'],
['MU', '51.52', '50.49', '52.31', '50.74'],
['NFLX', '490.10', '492.26', '511.52', '494.72', 'SUCCESS'],
['PCG', '9.49', '8.96', '9.52', '9.01'],
['PFE', '36.69', '35.87', '37.02', '36.05'],
['QQQ', '264.00', '263.27', '267.11', '264.58', 'SUCCESS'],
['ROKU', '153.36', '148.37', '153.70', '149.11'],
['SHOP', '952.83', '976.45', '1,036.25', '981.33', 'SUCCESS'],
['SPY', '325.01', '323.64', '325.47', '325.25', 'SUCCESS'],
['SQ', '126.99', '125.13', '130.80', '125.76'],
['T', '30.25', '29.58', '30.07', '29.73'],
['TSLA', '1,568.36', '1,646.56', '1,712.58', '1,654.79', 'SUCCESS'],
['TTWO', '153.06', '152.45', '154.47', '153.22', 'SUCCESS'],
['TWTR', '37.01', '36.03246', '36.7210083', '36.21'],
['WFC', '26.20', '24.45272', '25.0438213', '24.57'],
['WMT', '132.33', '130.8515', '132.522049', '131.51'],
]
}

List comprehension makes this pretty simple. Try the following:
keyword = "SUCCESS"
# PEP8 calls for lower_underscore_case here
second_list = [i[0] for i in stockList if keyword in i]
print(second_list)
For the proposed dictionary structure, you'd just access the key containing the list, since not every value in that dict is a list:
second_list = [i[0] for i in stockList["values"] if keyword in i]

Based upon your question understanding. Your question is divided into two parts, these are:
How to iterate over list of lists, and get the first item from the nested list, and store it in another list
How to iterate over dictionary item, to perform the same operation
If my understanding is right, then you might want to check this out.
Please note: I have not used variable keyword, simply used "SUCCESS", just replace keyword with "SUCCESS" in the code, and you are good to go.
1. FIRST SOLUTION
# to get nested list
for item in stockList:
# this checks whether SUCCESS is present inside a list
# python way of doing it
if "SUCCESS" in item: secondList.append(item[0])
print(secondList)
# OUTPUT
# >>> ['NFLX', 'QQQ', 'SHOP', 'SPY', 'TSLA', 'TTWO']
OR
You can do this in more pythonic way, that is to use List Comprehension
# single line approach, getting the same result
secondList = [item[0] for item in stockList if "SUCCESS" in item]
print(secondList)
# OUTPUT
# >>> ['NFLX', 'QQQ', 'SHOP', 'SPY', 'TSLA', 'TTWO']
2. SECOND SOLUTION
In order to get the result, first you need to assign the Dictionary to your variable, in my case, I have assigned to a variable called stockListDictionary
secondList = []
# to get a value from key specifically
# likt any dictionary key dictionary["key_name"]
for item in stockListDictionary["values"]:
if "SUCCESS" in item: secondList.append(item[0])
print(secondList)
# OUTPUT
# >>> ['NFLX', 'QQQ', 'SHOP', 'SPY', 'TSLA', 'TTWO']
OR
Using List Comprehension
secondList = [item[0] for item in stockListDictionary["values"] if "SUCCESS" in item]
print(secondList)
# OUTPUT
# >>> ['NFLX', 'QQQ', 'SHOP', 'SPY', 'TSLA', 'TTWO']

What about something like this?
keywords={"SUCCESS"}
d = # the dictionary
second_list = list()
for nested_lists in d["values"]:
for stock_info in nested_lists:
stock_ticker = stock_info[0]
if stock_ticker in keywords:
info = set(stock_info[1:])
if info & keywords:
second_list.append(stock_ticker)
Is this better? It should allow you to have more than one keyword.

Related

How to apply recursion over this problem and solve this problem

The Problem is:-
Given a digit string, return all possible letter combinations of each digits according to the buttons on a telephone, that the number could represent.
The returned strings must be lexicographically sorted.
Example-1 :-
Input : “23”
Output : ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Example-2 :-
Input : “9”
Output: [“w”, “x”, “y”, “z”]
Example-3 :-
Input : “246”
Output : ["agm", "agn", "ago", "ahm", ..., "cho", "cim", "cin" "cio"] {27 elements}
I've squeezed my brain on this, and I've tried a lot but I'm not getting ahead of this part, what I've tried is to use a recursive function that zips the individual letters of each digit with each other letters and use itertools.combinations() over it, but I'm unable to complete this function and I'm unable to get ahead of this.
What I've tried is :-
times, str_res = 0, ""
def getval(lst, times):
if times==len(lst)-1:
for i in lst[times]:
yield i
else:
for i in lst[times]:
yield i + getval(lst, times+1)
dct = {"2":("a","b","c"), "3":("d","e","f"), "4":("g","h","i"),
"5":("j","k","l"), "6":("m","n","o"), "7":("p","q","r","s"),
"8":("t","u","v"), "9":("w","x","y","z"), "1":("")}
str1, res = "23", []
if len(str1)==1:
print(dct[str1[0]])
else:
temp = [dct[i] for i in str1]
str_res = getval(temp, times)
print(str_res)
Please suggest me your ideas over this problem or in completing the function...
It's not itertools.combinations that you need, it's itertools.product.
from itertools import product
def all_letter_comb(s, dct):
for p in product(*map(dct.get, s)):
yield ''.join(p)
dct = {"2":("a","b","c"), "3":("d","e","f"), "4":("g","h","i"),
"5":("j","k","l"), "6":("m","n","o"), "7":("p","q","r","s"),
"8":("t","u","v"), "9":("w","x","y","z"), "1":("")}
for s in ['23', '9', '246']:
print(s)
print(list(all_letter_comb(s, dct)))
print()
Output:
23
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
9
['w', 'x', 'y', 'z']
246
['agm', 'agn', 'ago', 'ahm', 'ahn', 'aho', 'aim', 'ain', 'aio', 'bgm', 'bgn', 'bgo', 'bhm', 'bhn', 'bho', 'bim', 'bin', 'bio', 'cgm', 'cgn', 'cgo', 'chm', 'chn', 'cho', 'cim', 'cin', 'cio']
If I am not wrong this is leet code problem. You can find multiple answers there.

Python 3: How Do I Invert A Dictionary That Has A List As A Value

So for class I need to take a dictionary that has a list as a value and invert it. I have found several ways to do this, but the issue is when there are non-unique values. I found a way to do this but I feel like there must be much easier and streamlined ways to do this.
summon_locations = {
"Solaire": ['Gargoyles' ,'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers' ,'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'The Rotten'],
}
#Original dictionary
summon_locations = {
"Solaire": ['Gargoyles' ,'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers' ,'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'Abyss Watchers'],
}
#Dictionary with a non-unique value
def invert(d):
big_dict = {}
for k, v in d.items():
for i in v:
if i not in big_dict:
big_dict[i] = [k]
else:
big_dict[i].append(k)
return big_dict
print(invert(summon_locations))
Output Original:
{'Gargoyles': ['Solaire'], 'Gaping Dragon': ['Solaire'], 'Ornstein/Smough': ['Solaire'], 'Abyss Watchers': ['Gotthard'], 'Pontiff Sulyvahn': ['Gotthard'], 'Grand Archives': ['Gotthard'], 'Lost Sinner': ['Lucatiel'], 'Smelter Demon': ['Lucatiel'], 'The Rotten': ['Lucatiel']}
Output One non-unique value:
{'Gargoyles': ['Solaire'], 'Gaping Dragon': ['Solaire'], 'Ornstein/Smough': ['Solaire'], 'Abyss Watchers': ['Gotthard', 'Lucatiel'], 'Pontiff Sulyvahn': ['Gotthard'], 'Grand Archives': ['Gotthard'], 'Lost Sinner': ['Lucatiel'], 'Smelter Demon': ['Lucatiel']}
So it will just take the original key of a duplicate value and append it to a list. I have seen some cool ways to go about inverting dictionaries but they tend to fail here due to the lists.
You can use a defaultdict to remove the else statement and to check if the key exists. If it doesn't exists an empty list will be created.
from pprint import pprint
summon_locations = {
"Solaire": ['Gargoyles', 'Gaping Dragon', "Ornstein/Smough"],
"Gotthard": ['Abyss Watchers', 'Pontiff Sulyvahn', "Grand Archives"],
"Lucatiel": ['Lost Sinner', 'Smelter Demon', 'Abyss Watchers'],
}
if __name__ == '__main__':
from collections import defaultdict
inverted = defaultdict(list)
for key, values in summon_locations.items():
for value in values:
inverted[value].append(key)
pprint(inverted)
Output
defaultdict(<class 'list'>,
{'Abyss Watchers': ['Gotthard', 'Lucatiel'],
'Gaping Dragon': ['Solaire'],
'Gargoyles': ['Solaire'],
'Grand Archives': ['Gotthard'],
'Lost Sinner': ['Lucatiel'],
'Ornstein/Smough': ['Solaire'],
'Pontiff Sulyvahn': ['Gotthard'],
'Smelter Demon': ['Lucatiel']})
Which is similar to the the one-liner
[inverted[value].append(key) for key, values in summon_locations.items() for value in values]
But one liners are not always better, in this case I would stay with the two for loops.
You can replace your if else :
def invert(d):
big_dict = {}
for k, v in d.items():
for i in v:
big_dict[i] = big_dict.get(i, []) + [k]
return big_dict
However I can't find a way to skip one for.

How to remove or eliminate all dictionary which contains one list value from a list of dictionaries?

I have a list of dictionaries and I am looking to remove or eliminate all the dictionaries which contain one list-value from each dictionary in that list . This is an example of a dictionary which has one list-value ({'10.48.18.47': ['07:46:06']}). This is an example of list of dictionaries:
[{'10.0.0.155': ['19:48:46', '20:15:46', '19:49:37', '20:15:08', '19:48:46', '19:47:30', '19:49:13', '20:15:50', '19:45:34', '19:45:33', '19:49:13', '19:49:16', '19:49:36', '19:50:02', '19:54:25', '20:15:06', '19:45:25', '20:15:49', '19:55:10', '19:47:33'], '192.168.1.240': ['16:23:40', '16:23:39', '16:23:20'], '192.168.0.242': ['20:14:07', '20:14:09']}, {}, {'10.48.18.47': ['07:46:06']}, {}, {'0.0.0.0': ['21:19:02', '21:45:21', '21:22:04', '21:18:53', '21:38:47', '21:22:52', '21:38:49', '21:22:05', '21:18:55', '21:22:03', '21:18:45', '21:19:01', '21:22:53', '21:18:25', '21:38:51', '21:22:09', '21:18:15'], '192.168.1.193': ['20:09:24', '20:33:57', '20:09:13', '20:09:39', '20:09:29', '20:03:06', '20:09:33', '20:33:58', '20:09:19', '20:09:38', '20:09:37', '20:18:28', '20:09:17', '20:09:22', '20:33:59', '20:29:53', '20:07:47', '20:09:36', '20:18:29', '20:03:04', '20:34:00'], '172.16.12.31': ['18:57:32'], '192.168.1.120': ['20:43:06', '20:43:05', '20:43:04'], '192.168.1.186': ['20:18:36']}]
This is my code:
My_list = [mhist, mhist1,mhist2,mhist3,mhist4]
print (My_list)
while {} in My_list:
My_list.remove({})
for dect in My_list:
count = sum(len(v) for v in dect.values())
print (count)
You can try:
>>> data = [{'10.0.0.155': ['19:48:46', '20:15:46', '19:49:37', '20:15:08', '19:48:46', '19:47:30', '19:49:13', '20:15:50', '19:45:34', '19:45:33', '19:49:13', '19:49:16', '19:49:36', '19:50:02', '19:54:25', '20:15:06', '19:45:25', '20:15:49', '19:55:10', '19:47:33'], '192.168.1.240': ['16:23:40', '16:23:39', '16:23:20'], '192.168.0.242': ['20:14:07', '20:14:09']}, {}, {'10.48.18.47': ['07:46:06']}, {}, {'0.0.0.0': ['21:19:02', '21:45:21', '21:22:04', '21:18:53', '21:38:47', '21:22:52', '21:38:49', '21:22:05', '21:18:55', '21:22:03', '21:18:45', '21:19:01', '21:22:53', '21:18:25', '21:38:51', '21:22:09', '21:18:15'], '192.168.1.193': ['20:09:24', '20:33:57', '20:09:13', '20:09:39', '20:09:29', '20:03:06', '20:09:33', '20:33:58', '20:09:19', '20:09:38', '20:09:37', '20:18:28', '20:09:17', '20:09:22', '20:33:59', '20:29:53', '20:07:47', '20:09:36', '20:18:29', '20:03:04', '20:34:00'], '172.16.12.31': ['18:57:32'], '192.168.1.120': ['20:43:06', '20:43:05', '20:43:04'], '192.168.1.186': ['20:18:36']}]
>>> final_data = []
>>> for d in data:
... if len(d.values()) > 1:
... final_data.append(d)
...
>>> final_data
[{'10.0.0.155': ['19:48:46', '20:15:46', '19:49:37', '20:15:08', '19:48:46', '19:47:30', '19:49:13', '20:15:50', '19:45:34', '19:45:33', '19:49:13', '19:49:16', '19:49:36', '19:50:02', '19:54:25', '20:15:06', '19:45:25', '20:15:49', '19:55:10', '19:47:33'], '192.168.1.240': ['16:23:40', '16:23:39', '16:23:20'], '192.168.0.242': ['20:14:07', '20:14:09']}, {'0.0.0.0': ['21:19:02', '21:45:21', '21:22:04', '21:18:53', '21:38:47', '21:22:52', '21:38:49', '21:22:05', '21:18:55', '21:22:03', '21:18:45', '21:19:01', '21:22:53', '21:18:25', '21:38:51', '21:22:09', '21:18:15'], '192.168.1.193': ['20:09:24', '20:33:57', '20:09:13', '20:09:39', '20:09:29', '20:03:06', '20:09:33', '20:33:58', '20:09:19', '20:09:38', '20:09:37', '20:18:28', '20:09:17', '20:09:22', '20:33:59', '20:29:53', '20:07:47', '20:09:36', '20:18:29', '20:03:04', '20:34:00'], '172.16.12.31': ['18:57:32'], '192.168.1.120': ['20:43:06', '20:43:05', '20:43:04'], '192.168.1.186': ['20:18:36']}]
You can try this -
d = [{'10.0.0.155': ['19:48:46', '20:15:46', '19:49:37', '20:15:08', '19:48:46', '19:47:30', '19:49:13', '20:15:50', '19:45:34', '19:45:33', '19:49:13', '19:49:16', '19:49:36', '19:50:02', '19:54:25', '20:15:06', '19:45:25', '20:15:49', '19:55:10', '19:47:33'], '192.168.1.240': ['16:23:40', '16:23:39', '16:23:20'], '192.168.0.242': ['20:14:07', '20:14:09']}, {}, {'10.48.18.47': ['07:46:06']}, {}, {'0.0.0.0': ['21:19:02', '21:45:21', '21:22:04', '21:18:53', '21:38:47', '21:22:52', '21:38:49', '21:22:05', '21:18:55', '21:22:03', '21:18:45', '21:19:01', '21:22:53', '21:18:25', '21:38:51', '21:22:09', '21:18:15'], '192.168.1.193': ['20:09:24', '20:33:57', '20:09:13', '20:09:39', '20:09:29', '20:03:06', '20:09:33', '20:33:58', '20:09:19', '20:09:38', '20:09:37', '20:18:28', '20:09:17', '20:09:22', '20:33:59', '20:29:53', '20:07:47', '20:09:36', '20:18:29', '20:03:04', '20:34:00'], '172.16.12.31': ['18:57:32'], '192.168.1.120': ['20:43:06', '20:43:05', '20:43:04'], '192.168.1.186': ['20:18:36']}]
for dct in d:
for key in dct.copy():
if len(dct[key]) <= 1:
dct.pop(key,None)
The reason some keys with length less then 1 was left because there were multiple dicts inside the list

Create a dictionary from two lists having duplicate elements

Create a dictionary from two lists having duplicate elements where list 1 is the key of the new dictionary and for all strings in list 2 that exactly match list 1, append it to its values field for the keys in list 1. So, for example:
{'assembla':['assemblabase', 'assemblauploading']}
Like this, I want for each element in list 1
Stuck in this logic:
new_d = {}
for j in list2:
if j == list1 :
new_d['j'].get('j')
print(new_d)
List 1:
list1 = ['assembla', 'bitbucket', 'cloudapp', 'cloudforge', 'cloudinary', 'concur', 'confluence', 'convo', 'dochub', 'docstoc', 'docusign', 'draw.io', 'dropbox', 'egnyte', 'evernote', 'facebook', 'flickr', 'github', 'gitlab', 'glassdoor', 'globalmeet', 'gotowebinar', 'hightail', 'hootsuite', 'huddle', 'icloud', 'imgur', 'instagram', 'issuu', 'jumpshare', 'linkedin', 'lucidpress', 'mail.ru', 'maytech', 'meetup', 'mega', 'mendeley', 'mixi', 'myspace', 'ning', 'onehub', 'owncloud', 'pastebin', 'pinterest', 'prezi', 'proofhub', 'quip', 'quora', 'readytalk', 'reddit', 'renren', 'screencast', 'scribd', 'sendthisfile', 'sharevault', 'slack', 'slideshare', 'smartsheet', 'soundcloud', 'sourceforge', 'stocktwits', 'storify', 'surveymonkey', 'syncplicity', 'tableau', 'teamdrive', 'teamviewer', 'trello', 'tumblr', 'twitter', 'viber', 'vimeo', 'vine', 'virustotal', 'workday', 'yammer', 'youtube', 'zendesk', 'zenefits']
List 2:
list2 = ['2ch', '2chbase', '2chposting', '51.com', '51.commail', '51.combase', '51.combbs', '51.composting', '51.comwebdisk', '51.commusic', '51.comgames', 'adobeconnect', 'adobemeeting', 'adobemeetingdesktopsharing', 'adobemeetinguploading', 'adobemeetingfiletransfer', 'adobemeetingremotecontrol', 'adobeconnectnow', 'adobeconnectnowbase', 'adobeconnectnowfiletransfer', 'adobeconnectnowremotecontrol', 'adobecreativecloud', 'adobecreativecloudbase', 'adobecreativeclouduploading', 'aim', 'aimbase', 'aimvideo', 'aimaudio', 'aimfiletransfer', 'aimexpress', 'aimexpressbase', 'aimexpressfiletransfer', 'aliwangwang', 'aliwangwangbase', 'aliwangwangaudiovideo', 'aliwangwangfiletransfer', 'aliwangwangremotecontrol', 'amazonclouddrive', 'amazonclouddrivebase', 'amazonclouddriveuploading', 'amazonmusic', 'amazonmusicbase', 'amazonmusicstreaming', 'amebanow', 'amebanowbase', 'amebanowposting', 'assembla', 'assemblabase', 'assemblauploading', 'autodesk360', 'autodesk360base', 'autodesk360uploading', 'avayawebalive', 'avayawebalivebase', 'avayawebalivedesktopsharing', 'avayawebalivevoice', 'avayawebalivefiletransfer', 'bacnet', 'bacnetbase', 'bacnetackalarm', 'bacnetconfirmedcovnotify', 'bacnetconfirmedeventnotify', 'bacnetgetalarmsummary', 'bacnetgetenrollmentsummary', 'bacnetsubscribecov', 'bacnetatomicreadfile', 'bacnetatomicwritefile', 'bacnetaddlistelement', 'bacnetremovelistelement', 'bacnetcreateobject', 'bacnetdeleteobject', 'bacnetreadproperty', 'bacnetreadpropconditional', 'bacnetreadpropmultiple', 'bacnetwriteproperty', 'bacnetwritepropmultiple', 'bacnetdevicecommcontrol', 'bacnetconfirmedprivatexfer', 'bacnetconfirmedtextmessage', 'bacnetreinitializedevice', 'bacnetvtopen', 'bacnetvtclose', 'bacnetvtdata', 'bacnetauthenticate', 'bacnetrequestkey', 'bacnetreadrange', 'bacnetlifesafetyoperation', 'bacnetsubscribecovproperty', 'bacnetgeteventinformation', 'baiduhi', 'baiduhibase', 'baiduhiaudiovideo', 'baiduhifiletransfer', 'baiduhigames', 'bebo', 'bebomail', 'bebobase', 'beboposting', 'bitbucket', 'bitbucketbase', 'bitbucketuploading']
I believe this solves your problem:
new_dict = {}
for i in list1:
new_dict[i] = []
for j in list2:
if i in j:
new_dict[i].append(j)
Use a combined dict/list comprehension (it is shorter, but has worse readability):
new_dict = {key:[val for val in list2 if key in val and not key == val] for key in list1 if key in list2}
On my machine I get the following output:
{'assembla': ['assemblabase', 'assemblauploading'], 'bitbucket': ['bitbucketbase', 'bitbucketuploading']}
Updated with your more precise problem description. Just added a second condition within the list comprehension.
Use zip to create dict out to two list
a=[1,2]
b=["a","b"]
c=zip(a,b)
c=dict(c)

Removing a num from a string in a list of numbers

An example like:
print("1.", get_list_nums_without_9([589775, 677017, 34439, 48731548, 782295632, 181967909]))
print("2.", get_list_nums_without_9([6162, 29657355, 5485406, 422862350, 74452, 480506, 2881]))
print("3.", get_list_nums_without_9([292069010, 73980, 8980155, 921545108, 75841309, 6899644]))
print("4.", get_list_nums_without_9([]))
nums = [292069010, 73980, 8980155, 21545108, 7584130, 688644, 644908219, 44281, 3259, 8527361, 2816279, 985462264, 904259, 3869, 609436333, 36915, 83705, 405576, 4333000, 79386997]
print("5.", get_list_nums_without_9(nums))
I'm trying to get number list without 9. If the list is empty or if all of the numbers in the list contain the digit 9, the function should return an empty list. I tried the function below, it doesn't work.
def get_list_nums_without_9(a_list):
j=0
for i in a_list:
a_list[j]=i.rstrip(9)
j+=1
return a_list
expected:
1. [677017, 48731548]
2. [6162, 5485406, 422862350, 74452, 480506, 2881]
3. []
4. []
5. [21545108, 7584130, 688644, 44281, 8527361, 83705, 405576, 4333000]
your lists contain integers. To remove the ones containing 9 the best way is to test if 9 belongs to the number as string and rebuild the output using a list comprehension with a conditional.
(Besides, rstrip removes the trailing chars of a string. Not suitable at all for your problem)
def get_list_nums_without_9(a_list):
return [x for x in a_list if "9" not in str(x)]
testing with your data:
>>> numbers = [
... [589775, 677017, 34439, 48731548, 782295632, 181967909],
... [6162, 29657355, 5485406, 422862350, 74452, 480506, 2881],
... [292069010, 73980, 8980155, 921545108, 75841309, 6899644],
... [],
... [292069010, 73980, 8980155, 21545108, 7584130, 688644, 644908219,
... 44281, 3259, 8527361, 2816279, 985462264, 904259, 3869, 609436333,
... 36915, 83705, 405576, 4333000, 79386997]
... ]
>>> for i, l in enumerate(numbers, 1):
... print("{}. {}".format(i, get_list_nums_without_9(l)))
1. [677017, 48731548]
2. [6162, 5485406, 422862350, 74452, 480506, 2881]
3. []
4. []
5. [21545108, 7584130, 688644, 44281, 8527361, 83705, 405576, 4333000]
You don't want to replace anything in the list, you want to generate a new list based on what you detect in the old list:
def get_list_nums_without_9(numbers):
sans_9 = []
for number in numbers:
if '9' not in str(number):
sans_9.append(number)
return sans_9
This will get you an empty list if there are no valid numbers.

Resources