how to remove the [ ] symbol - python

I have this list with dictionary data type:
venueList = [{'VIP Room':10,'Executive Room':30,'Pool Site':50}]
And I have this program:
print([d['VIP Room'] for d in venueList])
where it prints:
[10]
how to remove the [] symbol and is there a much simpler ways to print it.Thanks

Assuming you have only 1 element(dict) in the list
venueList[0]['VIP Room']
#Output:
#10

Right now your list only has one element (it's a singleton list), so it might make sense to print just the lone element. However, consider what you want for when there is more than just one element.
k = [d['VIP Room'] for d in venueList]
First we start with that.
If you want to output them as a list, just print(k). However, if you want the [] gone and using commas for separation, you can do print(", ".join(str(e) for e in k)). If you want to print them with spaces as separation, you can do print(*k), which equates to calling print(k[0], k[1], ..., k[-1]).

for d in venueList:
print(d['VIP Room'])

Considering you have a list with only one element, and that element is a dict, you just need to unwrap the value, take the list away, and print the value assoc to the key you want:
venueList = [{'VIP Room':10,'Executive Room':30,'Pool Site':50}]
print(venueList.pop()['VIP Room'])
You can check it here: https://repl.it/NW0S/1

Related

Given two list of words, than return as dictionary and set together

Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list being usernames that is made out of the names of people. what i want to do is take does two list than convert them to a dictonary and set them together.
like this:
>>> name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
>>> username_list = ["alejon", "carli", "hanri"]
>>> create_username_dict(name_list, username_list)
{
"Albert Jones": "alejon",
"Carlos Lion": "carli",
"Hanna Richardo": "hanri"
}
i have tried look around on how to connect two different list in too one dictonary, but can't seem to find the right solution
If both lists are in matching order, i.e. the i-th element of one list corresponds to the i-th element of the other, then you can use this
D = dict(zip(name_list, username_list))
Use zip to pair the list.
d = {key: value for key,value in zip(name_list, username_list)}
print(d)
Output:
{'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Considering both the list are same length and one to one mapping
name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
username_list = ["alejon", "carli", "hanri"]
result_stackoverflow = dict()
for index, name in enumerate(name_list):
result_stackoverflow[name] = username_list[index]
print(result_stackoverflow)
>>> {'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Answer by #alex does the same but maybe too encapsulated for a beginner. So this is the verbose version.

Python: Index slicing from a list for each index in for loop

I got stuck in slicing from a list of data inside a for loop.
list = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']
what I am looking for is to print only key without it values (running/stopped)
Overall code,
for each in list:
print(each[:]) #not really sure what may work here
result expected:
init.svc.logd
anyone for a quick solution?
If you want print only the key, you could use the split function to take whatever is before : and then replace [ and ] with nothing if you don't want them:
list = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']
for each in list:
print(each.split(":")[0].replace('[','').replace(']','')) #not really sure what may work here
which gives :
init.svc.logd
init.svc.logd-reinit
You should probably be using a regular expression. The concept of 'key' in the question is ambiguous as there are no data constructs shown that have keys - it's merely a list of strings. So...
import re
list_ = ['[init.svc.logd]: [running]', '[init.svc.logd-reinit]: [stopped]']
for e in list_:
if r := re.findall('\[(.*?)\]', e):
print(r[0])
Output:
init.svc.logd
init.svc.logd-reinit
Note:
This is more robust than string splitting solutions for cases where data are unexpectedly malformed

How do I index f.items()?

I could run a for loop as such:
for v in f.items():
BUT, it takes too much time. I know I want the second object in f.items(). How to I directly get the second object and save it?
Im not sure what the syntax is: e.g is it f.items(2), f.items()[2]? None of these work so I was wondering what does.
If you want values(your 2nd objects) from f.items() you should use the below: -
for k,v in f.items()
Or if you want the 2nd item from f.items() you should use the below: -
f = {1:'A',2:'B',3:'C'}
for item in enumerate(f.items(),1):
k,v = item
if k == 2:
print(v)
Do still want to extract 2nd value from 2nd item ?
You can create a list and then index.
item = list(f.items())[1]
Lists are created often in python and this operation is relatively inexpensive. If your dictionary is large, you can create an iterator and take its second value.
i = iter(f.items())
next(i)
item = next(i)
But the dict would need to be rather large to make this the better option.

Separate elements divided by comma in a list

I have a list of strings that contains elements of the type
List=['name1,vol', 'name1,price','name2, vol', 'name2,price'.... ]
I would like to extract a list only of "names" which are the parts that actually change as the second components in each element have a fix pattern (here:vol, price). Notice that the "names" can obviously have different length. To sum up, I'd like to extract something like:
List_names=['name1', 'name2' ]
How can I do that?
What if I have something of the type:
List_tricky=[('name1', 'vol'), ('name1', 'price'),('name2', 'vol'), ('name2', 'price').... ]
Something like this?
List=['name1,vol', 'name1,price','name2, vol', 'name2,price']
names = []
for string in List:
name = string.split(',')[0]
names.append(name)
print(names)
For your 'tricky' case, you can try:
# initialize variables:
names = []
# iterate over each point (tuple):
for point in List:
# get name:
name = point[0]
# append to list:
names.append(name)
print(names)
You could turn it into a dict then back into a list using str.split. (No loop required as it does it efficiently for you) Use functools.partial to apply the split to each string instead of a lambda:
from functools import partial
list(dict(map(partial(str.split, sep=','), List)))
This works for either input but way more simple for the list of tuples:
>>> l = ['name1,vol', 'name1,price','name2, vol', 'name2,price'.... ]
>>> list(dict(map(partial(str.split, sep=','), List)))
['name1', 'name2']
>>> l = [('name1', 'vol'), ('name1', 'price'),('name2', 'vol'), ('name2', 'price').... ]
>>> list(dict(l))
['name1', 'name2']
Similar logic to #Daniel Sokol's answer , you can use a one liner :
list2 = [x.split(',')[0] for x in List]
To add on top of #Alireza Tajadod's already wonderful answer, you might want to apply conversion to a set, then back to a list to remove any possible duplication items, as suggested by #Cryptoharf84 in the comments.
names_list = list(set([entry.split(',')[0] for entry in List]))
The same logic with list comprehension can be applied to the trickier case.
names_list_2 = list(set([entry[0] for entry in List_tricky]))
To make list comprehension more explicit, you can also do the following:
names_list_3 = list(set([name for name, _ in List_tricky]))
The _ indicates that we are discarding the second value of the unpacked tuple.
Sets are useful because converting a list with duplicate elements into a set effectively removes any duplications.
As a tip, look for naming conventions in python. But never name variables starting with upper case, nor with existing class names.
I will try something like:
list_names = [s.split(',')[0].strip() for s in List]
list_unique_names(set(list_names))
split returns a list of "chunks" of the original string, and strip to remove whitespaces on beginning/end of the resulting string.
I will change your data structure to dict instead of list
d={'name1': ('vol', 'price'),'name2': ('vol', 'price'), .... }
In order to get just the names:
d.keys()
You can also use a .map() function:
# Case 1: List
all_names = map(lambda x :a.split(',')[0], List)
# Case 2: List_tricky
all_names = [i[0] for i in List_tricky]
# After the code is the same
unique_names = set(all_names)
List_names = list(unique_names)
print(List_names)

Finding values in a list of key/value pairs

I have 2 lists
old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]
I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.
I have tried the following and it doesn't work
for old_name, new_name in zip(old_name_list, new_name_list):
if old_name in new_name[0]:
print new_name[1]
Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.
Build a dict() based on your second list, and lookup in that.
old_name_list = ["a-1234", "a-1235", "a-1236"]
new_name_list = [("a-1235", "a-5321"), ("a-1236", "a-6321"), ("a-1234", "a-4321") ]
d = dict(new_name_list)
for n in old_name_list:
print d[n]
You do need to put quotes around strings like "a-1234".
Using a dictionary may be the best way to do this.
old_name_list = ['a-1234', 'a-1235', 'a-1236']
new_name_list = [('a-1235', 'a-5321'), ('a-1236', 'a-6321'), ('a-1234, a-4321')]
mapping = dict(new_name_list)
values = [mapping[item] if item in mapping for item in old_name_list]
print values
Use this:
found_items = [item[1] for item in new_name_list if item[0] in old_name_list]

Categories

Resources