Python looping list and append value to variable - python

I have a .csv file with IPs which I converted into a list with Python:
def ip_list():
iplist = []
with open("/path/to/file") as csvfile:
csvlist = csv.reader(csvfile)
for lists in csvlist:
for item in lists:
iplist.append(item)
return iplist
ip = ip_list()
print(ip)
>>> ["192.168.1.1", "192.168.1.2", ...]
Now I want to have every value in the list and append them to a given parameter each time.
Function for context:
def gencontent(ip, value1, value2, time):
content = [
{
"example": {
"ipadress": ip
}
}
]
return content
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
content = getcontent(ip[0-...], value1, value2, time)
I want loop content with each value in ip:
#Example list for reproduction
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
content = getcontent(ip[0-...], ...)
I do not want:
#Example list for reproduction
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
content1 = getcontent(ip[0], ...)
content2 = getcontent(ip[1], ...)
...
I want to loop content basically each time with a new ip value.
Thanks!

I don't know what the getcontent() function does, but why not loop through the items in your list using a list comprehension?
content = [getcontent(x) for x in ip]

If you simply want to index them, maybe you could convert to a tuple and use enumerate.
For example:
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
indexed_ip = enumerate(tuple(ip))
print(list(indexed_ip))
# OUTPUT:
# [(0, '192.168.1.1'), (1, '192.168.1.2'), (2, '192.168.1.3')]
Or if you want the index to start at 1, instead of 0:
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
indexed_ip = enumerate(tuple(ip), 1)
print(list(indexed_ip))
# OUTPUT:
# [(1, '192.168.1.1'), (2, '192.168.1.2'), (3, '192.168.1.3')]
Alternatively, maybe a dictionary work for you in this situation.
Here’s an example using dictionary comprehension:
ip_dict = { ip.index(ip_item): ip_item for ip_item in ip}
print(ip_dict)
# OUTPUT:
# {0: '192.168.1.1', 1: '192.168.1.2', 2: '192.168.1.3'}
You can name the keys for the dictionary, whatever you’d like. if you’re sent on content0, content1, etc, you could change the key value in the dict comprehension to something like f’content{str(ip.index(ip_item))}’. Then you could get the value from the ip_dict using ip_dict['content1'] and etc.

can you be more specific about content = getcontent(ip[0-...])?
i don't know whether i get you.
maybe something like this?
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
def getip(li):
for item in li:
yield(item)
ipgetter = getip(ip)
content = getcontent(next(ipgetter), value1, value2, time) # getcontent got "192.168.1.1"
content = getcontent(next(ipgetter), value1, value2, time) # getcontent got "192.168.1.2"
if loop is in an end, an StopIteration Exception will being raised

Related

How to dynamically apply variables to the values of a dictionary using Python and/or RobotFramework

Say I have a list of dictionaries:
URL_LIST = [
{'google': 'http://www.google.com/join'},
{'yahoo': 'http://www.yahoo.com/{0}/join'},
{'msn': 'http://www.msn.com/{0}/join'}
]
Now, I want to pass this dictionary to a python function, along with two other variables, so that the two variables replaces the {0}s in the 'yahoo' and 'msn' variables:
def apply_arguments (url_list, yahoo_subpage, msn_subpage):
#Do stuff
return url_list
So if the yahoo_suboage = 'aaa' and msn_subpage = 'bbb', I want the final result to be like this:
URL_LIST = [
{'google': 'http://www.google.com/join'},
{'yahoo': 'http://www.yahoo.com/aaa/join'},
{'msn': 'http://www.msn.com/bbb/join'}
]
I want to do it using either python or RobotFramework. Is that even possible?
I think your URL_LIST is unnecessarily nested, so I use a list in this answer.
lst = [
'http://www.google.com/join',
'http://www.yahoo.com/{0}/join',
'http://www.msn.com/{0}/join',
]
dct = {
'yahoo': 'aaa',
'msn': 'bbb',
}
def make_changes(lst, dct):
for i, url in enumerate(lst):
k = url.split('.')[1]
try:
lst[i] = url.replace('{0}', dct[k])
except:
pass
return lst
print(make_changes(lst, dct))
Output:
['http://www.google.com/join', 'http://www.yahoo.com/aaa/join', 'http://www.msn.com/bbb/join']

Python Dictionaries: Different way to iterate through a dict

I am searching for a different way to access every key in a dictionary within a for loop. Underneath, there is an example code, where I iterate through a dictionary and access every key with the help of a counter and a if statement. Is there another way to access the keys, without a counter or an if statement?
def string_to_dict(csv):
dict = []
tmp = csv.splitlines()
for i in tmp:
tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
tmp_i= i.split(",")
counter = 0;
for si in tmp_i:
if counter ==0:
tmp_dict["vorname"] = si
counter =counter + 1
elif counter == 1:
tmp_dict["nachname"] = si
counter = counter + 1
else:
tmp_dict["email"] = si
dict.append(tmp_dict)
csv = """Donald,Duck,d.duck#entenhausen.com
Wiley,Coyote,whiley#canyon.org
Road,Runner,roadrunner#canyon.org"""
There is no need for the loop if you already expect name, surname and email.
def string_to_dict(csv):
dict = []
tmp = csv.splitlines()
for i in tmp:
tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
tmp_i= i.split(",")
tmp_dict["vorname"] = tmp_i[0]
tmp_dict["nachname"] = tmp_i[1]
tmp_dict["email"] = tmp_i[2]
dict.append(tmp_dict)
We can keep iterating to improve the solution:
def string_to_dict(csv):
dict = []
tmp = csv.splitlines()
for i in tmp:
tmp_dict = {"vorname" : None, "nachname" : None, "email" : None};
tmp_i= i.split(",")
tmp_dict["vorname"] = tmp_i[0]
tmp_dict["nachname"] = tmp_i[1]
tmp_dict["email"] = tmp_i[2]
dict.append(tmp_dict)
And even more (if you want to use a protected keyword like dict, naming convention is to use an underscore after it):
def string_to_dict(csv):
dict_ = []
for line in csv.splitlines():
vor_name, nach_name, email = line.split(",")
dict_.append({"vorname" : vor_name, "nachname" : nach_name, "email" : email})
return dict_
And with list comprehensions:
def string_to_dict(csv):
def _parse_item(vor_name, nach_name, email):
return {"vorname" : vor_name, "nachname" : nach_name, "email" : email}
return [_parse_item(*line.split(",")) for line in csv.splitlines()]
If you want minimal changes to what you have done so far, you can just get list of keys and use the index value (counter variable in your case), something like this:
for i in tmp:
tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
tmp_i= i.split(",")
counter = 0;
keys = [*temp_dict.keys()] # List of Keys
for si in tmp_i:
tmp_dict[keys[counter]] = si # Key at index counter
counter += 1
dict.append(tmp_dict)
Sample Run:
>>string_to_dict(csv)
[{'vorname': ' Road', 'nachname': 'Runner', 'email': 'roadrunner#canyon.org'}, {'vorname': ' Road', 'nachname': 'Runner', 'email': 'roadrunner#canyon.org'}, {'vorname': ' Road', 'nachname': 'Runner', 'email': 'roadrunner#canyon.org'}]
Another Note: You're naming the variable as dict You should avoid that since it's a keyword in Python
Lets start with the fact that you are not trying to iterate over a dictionary but to create a list containing dictionary entries from a CSV format string.
secondly there are a lot of python syntactic mistakes and errors in your code.
Refrain from using reserved word such as "dict" as parameter names.
You can use this code snippet as a start if it helps you but I recommend brushing up on python syntax and best practices.
result = []
for line in csv.splitlines():
vorname, nachname, email = line.split(",")
result.append(
{"vorname": vorname.strip(), "nachname": nachname.strip(), "email": email.strip()})
This can be done also using list comprehension, but is much less readable

Passing multiple values from dictionary into method using loop

i have a question regarding adding dictionary key and value to method using loop
This is what i was thinking to write but it doesn't work how i want because it creates a packet just with one key/value every time
for key in packetData:
for name in packetData[key]:
packets = Ether()/IP()/UDP()/createsPacket(key, name=packetData[key][name])
print ("as name " + name + " \n as value " + str(packetData[key][name]))
Instead of writing this manually like that :
packets1 = Ether()/IP()/UDP()/createsPacket("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = Ether()/IP()/UDP()/createsPacket("72", PriceID = 123, Side = 12, MaxAmount = 123, MinAmount = 123, Price = 123000)
    json then converted to dictionary in python , this is data that i want to pass in
{
"65":{
"UserID":"vcjazfan",
"Password":"ejujwlhk",
"SessionID":115,
"ETX":192
},
"66":{
"UserID":"dzmtrssy",
"SessionID":35,
"Reason":"zbwivjcv",
"ETX":43
},
"72":{
"InstrumentIndex":171,
"PriceID":217,
"Side":226,
"MaxAmount":210,
"MinAmount":219,
"Price":47,
"PriceProvider":207,
"ETX":78
},
Made more generic for easier understanding, hoping it helps
Generic code
dictionary = {"65":{ "UserID":"vcjazfan", "Password":"ejujwlhk", "ETX":192} , "72":{ "InstrumentIndex":171, "PriceID":217, } }
#This is what i was thinking to write but it doesn't work how i want because it creates a packet just with one key/value every time
for key in dictionary:
for name in dictionary[key]:
value=dictionary[key][name]
packets = method(key, name=value) # in first iteration when key is 65 , name = "UserID" , value = "vcjazfan"
# in second iteration when key is 65 , name = "Password" , value = "ejujwlhk"
#Instead of writing this manually like that :
packets1 = method("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = method("72", InstrumentIndex = 123, PriceID = 12,)
This question solved my problem : How to pass dictionary items as function arguments in python?
solution to my original code:
Allpackets= []
for key in packetData:
Allpackets.append(packets/createsPacket(key, **packetData[key]))
Solution to generic one:
dictionary = {"65":{ "UserID":"vcjazfan", "Password":"ejujwlhk", "ETX":192} , "72":{ "InstrumentIndex":171, "PriceID":217, } }
Allpackets = []
for key in dictionary:
Allpackets.append( method(key, **dictionary))
#Instead of writing this manually like that :
packets1 = method("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = method("72", InstrumentIndex = 123, PriceID = 12,)

Python return value without inverted commas

I have csv file:
shack_imei.csv:
shack, imei
F10, "5555"
code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return value
list = str(get_imei_from_entered_shack(shack))
print list
which gives me "5555"
But I need this value in a list structure like this:
["5555"]
I've tried a lot of different methods, and they all end up with extra ' or""
EDIT 1:
new simpler code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
print imei
"5555"
list(imei) gives me ['"5555"'], I need it to be ["5555"]
You can change your "return" sentence:
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return [str(value)]
list = get_imei_from_entered_shack(shack)
print list
As far as I understand, you want to create a list containing the returned string, which you do with [ ]
list = [str(get_imei_from_entered_shack(shack))]
There are a few problems with this code, which are too long to tackle in comments
my_dict
my_dict = dict(reader) works only well if this csv is a collection of keys and values. If there are duplicate keys, this might give some problems
get_imei_from_entered_shack
Why this special method, instead of just asking my_dict the correct value. Even if you don't want it to trow an Exception when you ask for a shack that doesn't exists, you can use the dict.get(<key>, <default>) method
my_dict(shack, None)
does the same as your 4-line method
list
don't name variables the same as builtins
list2
if you want a list, you can do [<value>] or list(<value>) (unless you replaced list with your own variable assignment)
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
imei = imei.replace('"',"")
IMEI_LIST =[]
IMEI_LIST.append(imei)
print IMEI_LIST
['5555']

Extract a dictionary objects to a list

i need a small help to put the content returned from dictionary to 2 different list.
The code is :
for region in regions:
instance_information = {}
ip_dict = {}
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses().get('Addresses')
for address in addresses_dict:
if address.get('InstanceId'):
instance_information[address['InstanceId']] = [address.get('PublicIp')]
dex_dict = client.describe_tags().get('Tags')
for dex in dex_dict:
if instance_information.get(dex['ResourceId']):
instance_information[dex['ResourceId']].append(dex.get('Value'))
print (json.dumps(instance_information,indent=4))
This returns :
{
"i-c581ea32": [
"52.113.42.171",
"SDL Exclusive LB",
"pdx01-ms-pdl-lb01"
],
"i-b8601217": [
"52.26.21.83",
"pdx-LBi-b8609671",
"HAProxy Server",
"us-west-2",
"pdx02-cloud-trial01",
"subnet-d86be1af",
"us-west-2b"
],
"i-3c2b02ca": [
"52.13.84.44",
"pdx01-lb02"
],
"i-986fc140": [
"52.3.173.116",
"pdx-hprod-LBi-316fc340",
"HAProxy Server",
"us-west-2",
"pdx02-he-prod",
"subnet-bcdcd6cb",
"us-west-2b"
],
"i-035a2c4": [
"5.33.81.148",
"pdx-ece-prod-LBi-022c4",
"HAProxy Server",
"us-west-2",
"pdx02-emsce-prod
I just need to extract the IP and put it in a dict . I need to pass this IP to another def , How can this be done?
List comprehension is your tool:
iplist = [v[0] for v in instance_information.values()]
EDIT:
As you need, make a function that returns you the ips
def getIpFromRegions(regions):
for region in regions:
instance_information = {}
ip_dict = {}
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses().get('Addresses')
for address in addresses_dict:
if address.get('InstanceId'):
instance_information[address['InstanceId']] = [address.get('PublicIp')]
dex_dict = client.describe_tags().get('Tags')
for dex in dex_dict:
if instance_information.get(dex['ResourceId']):
instance_information[dex['ResourceId']].append(dex.get('Value'))
yield [v[0] for v in instance_information.values()]
EDIT2:
For all combined ip of region make a comprehension over your new function:
allip = [ip for ip in ips for ips in getIpFromRegions(regions)]
You may simple iterate over all the values in the given dictionary and select the first element as the IP to append it in a new list.
ip_list = [i[0]for i in instance_information.values()]
>> ['52.113.42.171', '52.26.21.83', '52.13.84.44', '5.33.81.148', '52.3.173.116']
Or if you need a dictionary like structure then you may try:
instance_information_ip = {i:instance_information[i][0] for i in instance_information}
>>> {'i-c581ea32': '52.113.42.171', 'i-b8601217': '52.26.21.83', 'i-3c2b02ca': '52.13.84.44', 'i-986fc140': '52.3.173.116', 'i-035a2c4': '5.33.81.148'}

Categories