Getting value from list using keys [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How do I get the value of an item in the list when requesting its "key"?
e.g. I currently have the following list:
[{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
How do I cycle through to print the title and revision of each file
Dictionary = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, ...
KeyList = ['rev', 'time', 'action', 'type', 'title']
for Key in KeyList:
print Key, "=", Dictionary[title]
And I am currently getting the following error:
Traceback (most recent call last):
File "P:/Scripts/PerforceSearchTool.py", line 45, in <module>
GetFiles()
File "P:/Scripts/PerforceSearchTool.py", line 28, in GetFiles
print Key, "=", Dictionary[depotFile]
NameError: global name 'depotFile' is not defined
The list in the end will contain thousands of files. I would like to be able to search the list for each of the files titles. And for the matching title return its title, depending on its action.

You can use a for loop:
mylist = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'}, {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for i in mylist:
print("Title: {}, Revision: {}".format(i["title"],i["rev"]))
Output:
Title: test.log, Revision: 1
Title: python.py, Revision: 0
Title: Hello.txt, Revision: 12

To print title and revision of each element you can do something like this:
a = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'}, {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for e in a:
print e['title'] + ' ' + e['rev']
It outputs this data:
test.log 1
python.py 0
Hello.txt 12

try this:
a = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for x in range(len(a)):
print a[x]['title']
print a[x]['rev']
Greetings

Related

Convert list of Dictionaries to comma separated string python

i'm trying to convert list of dictionaries to comma separated string , but some extra fields of dictionary are coming
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'}, {'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
expected output = TEST2,CUSTOMER/TEST 1
my script: s = [','.join(map(str,i.values())) for i in data]
output i'm getting : ['28,TEST 2,0,0', '27,CUSTOMER/TEST 1,0,0']
Try this:
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'}, {'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
print([d["name"] for d in data])
Output:
['TEST 2', 'CUSTOMER/TEST 1']
For the expected out, you simply need to get the value corresponding to the key name:
s = ','.join(i['name'] for i in data)
Data is defined as dictionary object. Apply elt for filter.
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'},
{'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
expected output = [elt["name"] for elt in data]
print(expected output)
output = ['TEST 2', 'CUSTOMER/TEST 1']

replacing keys from a dictionary inside a list python

I have a list inside a nested dictionary
body = {'Ready Date': '2020-01-31T12:00:00','Shipment Line List': [{'Description': 'Test', 'Weigth': '5',
'Height': '4.0','Length': '2.0', 'Width': '3.0'}, {'Description': 'Test', 'Weigth': '20', 'Height': '5',
'Length': '30', 'Width': '10']}
I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight"
I tried this approach, but I am not getting the expected output
key = {"Weigth":"Weight"}
def find_replace(dict_body, dictionary):
# is the item in the dict?
for item in dict_body:
# iterate by keys
if item in dictionary.keys():
# look up and replace
dict_body = dict_body.replace(item, dictionary[item])
# return updated dict
return dict_body
a = find_replace(body,key)
print(a)
I think a better idea in this particular case is to treat everything as a string, replace and back as a dictionary. Because if you have multiple nested keys, it might be just be easier this way in two lines of code:
from ast import literal_eval
body = literal_eval(str(body).replace("Weigth","Weight"))
This outputs:
{'Ready Date': '2020-01-31T12:00:00',
'Shipment Line List': [{'Description': 'Test',
'Height': '4.0',
'Length': '2.0',
'Weight': '5',
'Width': '3.0'},
{'Description': 'Test',
'Height': '5',
'Length': '30',
'Weight': '20',
'Width': '10'}]}
I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight"
something like the below
body = {'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Weigth': '5',
'Height': '4.0', 'Length': '2.0', 'Width': '3.0'},
{'Description': 'Test', 'Weigth': '20',
'Height': '5',
'Length': '30', 'Width': '10'}]}
for entry in body['Shipment Line List']:
entry['Weight'] = entry['Weigth']
del entry['Weigth']
print(body)
output
{'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Height': '4.0', 'Length': '2.0', 'Width': '3.0', 'Weight': '5'}, {'Description': 'Test', 'Height': '5', 'Length': '30', 'Width': '10', 'Weight': '20'}]}

Why only last element is printing while using function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I need to get the value for business' name and append it to a list.
I need to get the value policies and append to a list after checking parent.
if parent is Marketing name has to added to level1.
if parent is Advertising name has to added to level2.
if some place Business is [] I need to pass None instead of Null List
Also need to check key exists or not for some keys there is a chance of missing policies, business
dictionary is below
If in the list contains same elements example 'Business':['Customer', Customer] then only one element has to take
searchtest = [
{'_index': 'newtest',
'_type': '_doc',
'_id': '100',
'_score': 1.0,
'_source': {'id': '100',
'name': 'A',
'policies': [
{
'id': '332',
'name': 'Second division',
'parent': 'Marketing'},
{'id': '3323', 'name':
'First division',
'parent': 'Marketing'}
]
}
},
{'_index': 'newtest',
'_type': '_doc',
'_id': '101',
'_score': 1.0,
'_source': {
'id': '101',
'name': 'B',
'Business': [{'id': '9'}, {'id': '10', 'name': 'Customer'}],
'policies': [{'id': '332', 'name': 'Second division', 'parent': 'Marketing'}, {'id': '3323', 'name': 'First division', 'parent': 'Advertising'}]}}]`
Code is below
def business(searchtest):
for el in searchtest:
Business_List = []
if 'Business' in el['_source']:
for j in el['_source']['Business']:
if 'name' in j:
Business_List.append(j['name'])
else:
Business_List.extend([])
return Business_List
def policy(searchtest):
for el in searchtest:
level1= []
if 'policies' in el['_source']:
for j in el['_source']['policies']:
if 'parent' in j:
if 'Marketing' in j['parent'] :
level1.append(j['name'])
else:
level1.extend([])
level2= []
if 'policies' in el['_source']:
for j in el['_source']['policies']:
if 'parent' in j:
if 'Advertising' in j['parent']:
level2.append(j['name'])
else:
level2.extend([])
return [level1, level2]
def data_product(searchtest):
resp = []
for el in searchtest:
d = {
'id' : el['_source']['id'],
'name' : el['_source']['name'],
'Business' : business(searchtest),
'level1' : policy(searchtest)[0],
'level2' : policy(searchtest)[1]
}
resp.append(d)
return resp
if __name__ == "__main__":
import pprint
pp = pprint.PrettyPrinter(4)
pp.pprint(data_product(searchtest))
My output
[ { 'Business': [],
'id': '101',
'level1': ['Second division'],
'level2': ['First division'],
'name': 'B'}]
Expected out
[ { 'Business': [],
'id': '100',
'level1': ['Second division','First division'],
'level2': [],
'name': 'A'},
{ 'Business': ['Customer'],
'id': '101',
'level1': ['Second division'],
'level2': ['First division'],
'name': 'B'}]
if resp.append(d) is put inside the loop then only one id is repeating?
my whole code with change
searchtest = [{'_index': 'newtest',
'_type': '_doc',
'_id': '100',
'_score': 1.0,
'_source': {'id': '100',
'name': 'A',
'policies': [{'id': '332',
'name': 'Second division',
'parent': 'Marketing'},
{'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}},
{'_index': 'newtest',
'_type': '_doc',
'_id': '101',
'_score': 1.0,
'_source': {'id': '101',
'name': 'B',
'Business': [{'id': '9'}, {'id': '10', 'name': 'Customer'}],
'policies': [{'id': '332',
'name': 'Second division',
'parent': 'Marketing'},
{'id': '3323', 'name': 'First division', 'parent': 'Advertising'}]}}]
def business(el):
Business_List = []
# for el in searchtest:
if 'Business' in el['_source']:
for j in el['_source']['Business']:
if 'name' in j:
Business_List.append(j['name'])
else:
Business_List.extend([])
return Business_List
def policy(searchtest):
for el in searchtest:
level1 = []
if 'policies' in el['_source']:
for j in el['_source']['policies']:
if 'parent' in j:
if 'Marketing' in j['parent']:
level1 .append(j['name'])
else:
level1 .extend([])
level2 = []
if 'policies' in el['_source']:
for j in el['_source']['policies']:
if 'parent' in j:
if 'Advertising' in j['parent']:
level2.append(j['name'])
else:
level2.extend([])
return [level1, level1 ]
def data_product(searchtest):
resp = []
for el in searchtest:
d = {
'id': el['_source']['id'],
'name': el['_source']['name'],
'Business': business(el),
'level1': policy(searchtest)[0],
'level2': policy(searchtest)[1]
}
resp.append(d)
return resp
if __name__ == "__main__":
import pprint
pp = pprint.PrettyPrinter(4)
pp.pprint(data_product(searchtest))
output:
[ { 'Business': [],
'id': '100',
'level1': ['Second division'],
'level2': ['First division'],
'name': 'A'},
{ 'Business': ['Customer'],
'id': '101',
'level1': ['Second division'],
'level2': ['First division'],
'name': 'B'}]

How to access Nested Dictionary values through index

Im building a scanner using python-nmap libary. Here's the code :
import nmap
import json
def Nmap_Recon(host, port):
nm = nmap.PortScanner()
lol = nm.scan(host, '22-443')
print(lol['scan'])
Nmap_Recon('www.stuxnoid.org',80)
Output :
{'77.72.0.90': {'hostnames': [{'name': 'www.stuxnoid.org', 'type': 'user'}, {'name': 'carbon.cloudhosting.co.uk', 'type': 'PTR'}], 'addresses': {'ipv4': '77.72.0.90'}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'syn-ack'}, 'tcp': {25: {'state': 'open', 'reason': 'syn-ack', 'name': 'smtp', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}, 80: {'state': 'open', 'reason': 'syn-ack', 'name': 'http', 'product': 'imunify360-webshield/1.6', 'version': '', 'extrainfo': '', 'conf': '10', 'cpe': ''}, 443: {'state': 'open', 'reason': 'syn-ack', 'name': 'https', 'product': 'imunify360-webshield/1.6', 'version': '', 'extrainfo': '', 'conf': '10', 'cpe': ''}}}}
I guess the output is in dictionary format. The problem is, I want to display only the open port details. But the port details are nested inside the dict_key IP address (77.72.0.90) and It keeps changing with the domain I pass. How to access those Open port details and display them?
if your question is how to get first item out of a dictionary (arbitrary item prior to python 3.6) it can be done so:
next(iter(lol['scan'].values()))
or, destructively (this will return last item):
lol['scan'].popitem()[1]

How to extract the uris lists by regex? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my python code , I get strings from the text file like :
a = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.single.com'}]}]"
b ="[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]}]"
c ="[{'index': '1', 'selected': 'true', 'length': '103674793', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/002.mp3', 'uris': []}, {'index': '2', 'selected': 'true', 'length': '62043128', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/004.mp3', 'uris': []}, {'index': '3', 'selected': 'true', 'length': '57914945', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/003.mp3', 'uris': []}]"
I want to get the text of the value uris , the output should looks like :
a = [{'status': 'used', 'uri': 'http://www.single.com'}]
b = [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]
c = [[],[],[]]
Many hours I spent in failed trials to get this result by using the string functions ,
uris = str.split('}, {')
for uri in uris :
uri = uri.split(',')
# and so on ...
but , it work so bad especially in the second case , I hope that anyone can do it by regex or any other way.
They are all python literals. You can use ast.literal_eval. No need to use regular expression.
>>> a = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.single.com'}]}]"
>>> b = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]}]"
>>> c = "[{'index': '1', 'selected': 'true', 'length': '103674793', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/002.mp3', 'uris': []}, {'index': '2', 'selected': 'true', 'length': '62043128', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/004.mp3', 'uris': []}, {'index': '3', 'selected': 'true', 'length': '57914945', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/003.mp3', 'uris': []}]"
>>> import ast
>>> [x['uris'] for x in ast.literal_eval(a)]
[[{'status': 'used', 'uri': 'http://www.single.com'}]]
>>> [x['uris'] for x in ast.literal_eval(b)]
[[{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]]
>>> [x['uris'] for x in ast.literal_eval(c)]
[[], [], []]
in javascript you can do this
a = a.replace(/^.*uris[^[]*(\[[^\]]*\]).*$/, '\1');
if php would be this a way
$a = preg_replace('/^.*uris[^[]*(\[[^\]]*\]).*$/', '\1', $a);
edit: well I see, it wouldn't do your complete task for 'c' -.-

Categories

Resources