How to append values to set() to the end in python? - python-3.x

Have got a item = set(), need to append values to this 'item' to the end. But set() append it to first position pushing already present values to last as shown below.
item = {'Mango'}
item.add('Apple')
#Returns
{'Apple','Mango'}
#Expected output
{'Mango','Apple'}
Even tried item.update(['Apple']) doesn't work.

It looks like you want a data structure that has an ordered sequence. You can do this with lists instead of a set, and use .append to add things to the end of the list:
item = ['Mango', 'Apple']
item.append('Pear')
#Output
['Mango', 'Apple', 'Pear']

Related

How to combine elements in set and a string to a list in python?

Have got a set() like
item = {'Apple','Lemon'}
and a string flow='Mango'
need to combine both to form a list like below
result = ['Mango','Apple','Lemon']
tried the code result = [flow ,item] which doesn't work out.
Help me through this. Thanks!
You can unpack the set into a new list that includes flow:
result = [flow, *item]
Add item to the set, conver the set to a list:
item.add(flow)
list(item)
# ['Apple', 'Mango', 'Lemon']
Or convert the set to a list and concatenate it with a list of flow:
[flow] + list(item)
# ['Mango', 'Apple', 'Lemon']
The second approach preserves the original set.

Iterating thru a not so ordinary Dictionary in python 3.x

Maybe it is ordinary issue regarding iterating thru a dict. Please find below imovel.txt file, whose content is as follows:
{'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
As you can see this is not a ordinary dictionary, with a key value pair; but a key with a list as key and another list as value
My code is:
#/usr/bin/python
def load_dict_from_file():
f = open('../txt/imovel.txt','r')
data=f.read()
f.close()
return eval(data)
thisdict = load_dict_from_file()
for key,value in thisdict.items():
print(value)
and yields :
['primeiro', 'segundo', 'terceiro'] ['101', '201', '301']
I would like to print a key,value pair like
{'primeiro':'101, 'segundo':'201', 'terceiro':'301'}
Given such txt file above, is it possible?
You should use the builtin json module to parse but either way, you'll still have the same structure.
There are a few things you can do.
If you know both of the base key names('Andar' and 'Apto') you can do it as a one line dict comprehension by zipping the values together.
# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# One line dict comprehension
newdict = {key: value for key, value in zip(thisdict['Andar'], thisdict['Apto'])}
print(newdict)
If you don't know the names of the keys, you could call next on an iterator assuming they're the first 2 lists in your structure.
# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# create an iterator of the values since the keys are meaningless here
iterator = iter(thisdict.values())
# the first group of values are the keys
keys = next(iterator, None)
# and the second are the values
values = next(iterator, None)
# zip them together and have dict do the work for you
newdict = dict(zip(keys, values))
print(newdict)
As other folks have noted, that looks like JSON, and it'd probably be easier to parse it read through it as such. But if that's not an option for some reason, you can look through your dictionary this way if all of your lists at each key are the same length:
for i, res in enumerate(dict[list(dict)[0]]):
ith_values = [elem[i] for elem in dict.values()]
print(ith_values)
If they're all different lengths, then you'll need to put some logic to check for that and print a blank or do some error handling for looking past the end of the list.

Python3 print selected values of dict

In this simple code to read a tsv file of many columes:
InColnames = ['Chr','Pos','Ref','Alt']
tsvin = csv.DictReader(fin, delimiter='\t')
for row in tsvin:
print(', '.join(row[InColnames]))
How can I make the print work ?
The following will do:
for row in tsvin:
print(', '.join(row[col] for col in InCOlNames))
You cannot pass a list of keys to the dict's item-lookup and magically get a list of values. You have to somehow iterate the keys and retrieve each one's value individually. The approach at hand uses a generator expression for that.

Adding the results of a for loop to the same key in a nested dictionary

I have a dictionary where it includes few sub-dictionaries in it. Each sub-dictionary has many keys. After running a for loop with an if condition too, the results are generated. I want to add ALL the results to under the desired key; but all what my code actually does is adding the result of the last iteration of the loop thereby replacing the value of the previous iteration.
But, actually, i want to print all the results.
for item in list1: #item is a tuple & list1 has tuples in it
if item == node_pair: #node pair is another tuple
high_p[i]["links"] = link_name #"links" is the key
desired output:
"links": [link_name1, link_name2, link_name3]
what i get:
"links" : link_name3
Please guide me..
So each sub-dictionary needs to have lists as values. You could pre-populate each sub-dictionary with lists ahead of time, but it's easier to create them on demand using setdefault.
for item in list1:
if item == node_pair:
high_p[i].setdefault("links", []).append(link_name)

Indexing the list in python

record=['MAT', '90', '62', 'ENG', '92','88']
course='MAT'
suppose i want to get the marks for MAT or ENG what do i do? I just know how to find the index of the course which is new[4:10].index(course). Idk how to get the marks.
Try this:
i = record.index('MAT')
grades = record[i+1:i+3]
In this case i is the index/position of the 'MAT' or whichever course, and grades are the items in a slice comprising the two slots after the course name.
You could also put it in a function:
def get_grades(course):
i = record.index(course)
return record[i+1:i+3]
Then you can just pass in the course name and get back the grades.
>>> get_grades('ENG')
['92', '88']
>>> get_grades('MAT')
['90', '62']
>>>
Edit
If you want to get a string of the two grades together instead of a list with the individual values you can modify the function as follows:
def get_grades(course):
i = record.index(course)
return ' '.join("'{}'".format(g) for g in record[i+1:i+3])
You can use index function ( see this https://stackoverflow.com/a/176921/) and later get next indexes, but I think you should use a dictionary.

Resources