Python - Check if String is in Dictionary Value when Value is a list - python-3.x

I am trying to resolve the following: I created a list of the books in the Bible. I also created a Dictionary which has a Key and a Value which is a reference to the list created.
I would like to see if a string value is present in the dictionary, if present, return the key of the value.
Here is my code:
# Dict List for bible
BIBLE_BOOKS_LIST_DICT = [
("Genesis"), ("Exodus"), ("Leviticus"),
("Numbers"), ("Deuteronomy"), ("Joshua"),
("Judges"), ("1 Samuel"), ("2 Samuel"),
("1 Kings"), ("2 Kings"), ("1 Chronicles"),
("2 Chronicles"), ("Ezra"), ("Nehemiah"),
("Esther"), ("Job"), ("Psalms"), ("Proverbs"),
("Ecclesiastes"), ("Song of Solomon"),
("Isaiah"), ("Jeremiah"), ("Lamentations"),
("Ezekiel"), ("Daniel"), ("Hosea"), ("Joel"),
("Amos"), ("Obadiah"), ("Jonah"), ("Micah"),
("Nahum"), ("Habakkuk"), ("Zephaniah"),
("Haggai"), ("Zechariah"), ("Malachi"),
("Matthew"), ("Mark"), ("Luke"), ("John"),
("Acts"), ("Romans"), ("1 Corinthians"),
("2 Corinthians"), ("Galatians"), ("Ephesians"),
("Philippians"), ("Colossians"), ("1 Thessalonians"),
("2 Thessalonians"), ("1 Timothy"), ("2 Timothy"),
("Titus"), ("Philemon"), ("Hebrews"), ("James"),
("1 Peter"), ("2 Peter"), ("1 John"), ("2 John"),
("3 John"), ("Jude"), ("Revelation")
]
# Dict for bible categories
BIBLE_BOOKS_DICT = {
'The Law':BIBLE_BOOKS_LIST_DICT[:5],
'OT History':BIBLE_BOOKS_LIST_DICT[5:16],
'Poetry':BIBLE_BOOKS_LIST_DICT[16:21],
'Major Prophets':BIBLE_BOOKS_LIST_DICT[21:26],
'Minor Prophets':BIBLE_BOOKS_LIST_DICT[26:38],
'Gospels':BIBLE_BOOKS_LIST_DICT[38:42],
'NT History':BIBLE_BOOKS_LIST_DICT[42:43],
'Pauline Epistles':BIBLE_BOOKS_LIST_DICT[43:52],
'Pastoral Letters':BIBLE_BOOKS_LIST_DICT[52:55],
'General Epistles':BIBLE_BOOKS_LIST_DICT[55:64],
'Prophecy':BIBLE_BOOKS_LIST_DICT[64:65]
}
I've been working on this for hours but have not found any solution!
My logic is,
if "Matthew" in BIBLE_BOOKS_DICT.values():
print *the key related to that value*
Thank you!

How about this, using the dict.items() method:
for key, value in BIBLE_BOOKS_DICT.items():
if "Matthew" in value:
print(key)

If you want to be able to look up by book, and return a category, you need to be storing the books as the keys in the dictionary:
BIBLE_BOOKS_DICT = {
"Matthew": 'Gosphels'
"Revelation": 'Prophecy'
# etc...
"1 John": 'Gosphels'
Dictionaries are able to look up a value given a key in very quick runtime (e.g. constant). But to look up a key given a value, you would essentially have to iterate over all of the values, and then back-map the found value to its key. With the above dictionary your lookup logic would be:
# Look up the key, and assign its value to a variable
result = BIBLE_BOOKS_DICT.get("Matthew")
# Searched keys that don't exist in the dictionary will return None.
if result is not None:
print result
Let me know if any of this doesn't make sense, and I'm happy to elaborate further!

Someone was faster.
input = 'Matthew'
for k, v in BIBLE_BOOKS_DICT.items():
if input in v:
print(k)
But I have a function.
def get_cat(book):
for k, v in BIBLE_BOOKS_DICT.items():
if book in v:
return k
print(get_cat('Matthew'))
Output
Gospels
Gospels

Related

Python Iterating through List of List

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.

Getting IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

I'm getting this index error when I run this function. This function finds the average rent prices of a zipcode of a city. I have a dictionary of cities called city with zipcode as the key and city name as the value. There are multiple zipcodes for some cities and arrRent is a array with lists of rents of houses of the city and I want to find the average rent price.
def meanPrice(self, city):
total = 0
cityLoc = 0
for keys, cities in self.city.items():
if self.city[keys] == city:
for i in self.arrRent[cityLoc]:
total += int(self.arrRent[cityLoc][i])
mean = total / i
print(total / i)
else:
cityLoc += 1
Here's a snippet of the dictionary:
{'95129': 'San Jose'}
{'95128': 'San Jose'}
{'95054': 'Santa Clara'}
{'95051': 'Santa Clara'}
{'95050': 'Santa Clara'}
and here's a snippet of the array:
[['2659' '2623.5' '2749.5' '2826.5' '2775' '2795' '2810' '2845' '2827'
'2847' '2854' '2897.5' '2905' '2925' '2902.5' '2869.5']
['3342.5' '3386' '3385' '3353' '3300' '3190' '3087.5' '3092' '3170'
'3225' '3340' '3315' '3396' '3470' '3480' '3380']
['2996' '2989' '2953' '2950' '2884.5' '2829' '2785' '2908' '2850' '2761'
'2997.5' '3020' '2952' '2997.5' '2952' '2923.5']
['2804.5' '2850.5' '2850' '2850' '2867' '2940' '2905' '2945' '2938'
'2860' '2884' '2946' '2938' '2986.5' '2931.5' '3032.5']
['2800' '3074' '2950' '2850' '2850' '2875' '2757' '2716' '2738.5' '2696'
'2809' '2891' '3000' '2960' '2950' '2831']]
I see 2 issues:
Issue in your list 'arrRent': It is supposed to be a list of lists, containing rents. But the different rents are not separated by comma in your list:
[['2659' '2623.5' '2749.5' '2826.5' '2775' '2795' '2810' '2845' '2827'
'2847' '2854' '2897.5' '2905' '2925' '2902.5' '2869.5']
['3342.5' '3386' '3385' '3353' '3300' .......
Your issue in code seems to be in this block of code. i is the actual rent here, not the index:
for i in self.arrRent[cityLoc]:
total += int(self.arrRent[cityLoc][i])
Change it to this:
for i in self.arrRent[cityLoc]:
total += int(i)

how could I make list of lists from neo4j record

I am facing list manipulation from loop iteration. I am trying to populate a list from Neo4j record
myquery="""MATCH (c :Customer {walletId:$item})-[:MR|:SENDS_MONEY]-(d)-[:PAYS]->(m)
WHERE NOT (c)-[]-(m)
RETURN c.walletId, m.walletId, m.name, COUNT(m.name) ORDER BY COUNT(m.name) DESC LIMIT 30"""
result=graphdbsessionwallet.run(myquery,item=item)
#print(result)
for record in result:
print(list(record))
and my current result is
['01302268120', '01685676658', 'Shojon Medical Hall', 6]
['01302268216', '01733243988', 'APEXFOOTWEAR LIMITED', 1]
and so on
desired
[['01302268120', '01685676658', 'Shojon Medical Hall', 6],['01302268216', '01733243988', 'APEXFOOTWEAR LIMITED', 1]]
I want to put this lists into one list , kindly help me to solve this
You can modify your query to return the list with the help of COLLECT clause:
MATCH (c :Customer {walletId:$item})-[:MR|:SENDS_MONEY]-(d)-[:PAYS]->(m)
WHERE NOT (c)-[]-(m)
WITH c, m, COUNT(m.name) as cnt
ORDER BY cnt DESC
RETURN COLLECT([c.walletId, m.walletId, m.name, cnt])
LIMIT 30

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)

Python 3: Accesing values in key in dictionary

automobiles = {
'germany': ['bmw', 'audi', 'mercedes benz'],
'japan': ['honda', 'toyota', 'subaru'],
'united states': ['ford', 'gm', 'buick'],
'italy': ['alfa romeo', 'ferrari', 'maserati'],
'great britain': ['jaguar', 'mini', 'aston martin'],
}
How can I access individual values in the different keys? (example: Who do I access the 'audi' in the germany key or 'buick' in the united states key?
So you have a dictionary who's keys are strings and who's values are lists.
To access 'audi' you can do this:
print(automobiles['germany'][1])
# which prints audi
Syntax: command(dict['key'][index])
In your case this would translate to:
print(automobiles['germany'][1])
'audi'
print(automobiles['united states'][2])
'buick'
The values stored in your dictionary are stored as lists. You can access elements in a list like list[n] where n is the index of the value you wish to access. Indexes start at 0 for python.

Resources