I have a dict that contains site location names and key codes
i'm trying to pull the site location names (which are values) out of the dict and make a simple list.
I have this code which prints exactly what i want:
for s in mydict['mykey']:
print(s['site'])
site1
site2
site3
site4
but when i try to do something like this:
for s in mydict['mykey']:
mylist = list(s['site'])
or
for s in mydict['mykey']:
mylist2 = (s['site'])
i only get the last value:
mylist
['s', 'i', 't', 'e', '4']
mylist2
'site4'
Basically just looking to have the sites in a list, one per line
Use a list comprehension:
mylist = [s['site'] for s in mydict['mykey']]
This is the equivalent of:
mylist = []
for s in mydict['mykey']:
mylist.append(s['site'])
Related
I'm currently trying to wrap my head around list comprehensions and try to get some practice by taking examples and form loops out of comprehensions and vice versa. Probably a really easy mistake, or a forest for the trees situation. Take the following expression taken from an example project:
rows = []
data = ['a', 'b']
res = ['1', '2']
rows.append({data[counter]: res[counter] for counter, _ in enumerate(data)})
print(rows):
[{'a': '1', 'b': '2'}]
How do i do this as a for loop? The following wraps each loop into a curly bracket instead of both.
for counter, _ in enumerate(data):
rows.append({data[counter]: res[counter]})
print(rows):
[{'a': '1'}, {'b': '2'}]
Am i missing something? Or do i have to merge the items by hand when using a for loop?
The problem in your code is that you create a dictionary for each item in data and append it to rows in each iteration.
In order to achieve the desired behaviour, you should update the same dict in each iteration and after you finish working on your dictionary, only then you should append it to rows.
Try this:
rows = []
data = ['a', 'b']
res = ['1', '2']
payload = {}
for counter, val in enumerate(data):
payload[val] = res[counter]
rows.append(payload)
Another compact way to write it might be:
rows.append(dict(zip(data,res)))
On every iteration of for loop you are creating a new dictionary and appending it into a list if you want to store a whole dictionary in a list then You should try something like that it outputs as you expected:
rows = []
data = ['a', 'b']
res = ['1', '2']
myDict = {}
for counter, _ in enumerate(data):
myDict[data[counter]]= res[counter]
rows.append(myDict)
print(rows)
Output:
[{'b': '2', 'a': '1'}]
I have done a large amount of searching but cannot find what I am after. I am using Iron Python.
I have a large list of strings (MyList) that I have extracted and I would like to see if there are values that contain the Items in the SearchStrings Dictionary. The searchStrings Dictionary could have over 500 items within.
MyList = ["123steel","MylistConcrete","Nothinginhere","45","56","steel","CONCRETE"]
SearchStrings = {'concrete' : 'C','CONCRETE' : 'C','Steel' : 'S', 'STEEL' : 'S'}
I need to return the index and then matching code from the SearchString.
i.e If we find 'MylistConcrete' i will know the index '1' and can return 'C'
I hope this makes sense to everyone. Let me know if you need any clarification
Thanks in Advance,
Geoff.
First of all, I'd suggest you to use string.lower() to eliminate case dependencies in the search. This will make your dictionary smaller and more manageable.
Then you can use a simple map function to create a new array with your values while preserving the index (or alter the original should you require that).
MyList = ["123steel","MylistConcrete","Nothinginhere","45","56","steel","CONCRETE"]
SearchStrings = {'concrete' : 'C', 'steel' : 'S'}
def check_search_strings(x):
for k, v in SearchStrings.items():
if k in x.lower():
return v
return None
indexes = list(map(check_search_strings, MyList))
print (indexes)
Iterate over your items in MyList and check for every item (lowercase) if any of the dict's (lowercase) keys is in it. Then replace.
This assumes that you don't have different values for identical words as keys (except for lower- / uppercase difference)
my_list = ["123steel", "MylistConcrete", "Nothinginhere", "45", "56", "steel", "CONCRETE"]
search_strings = {'concrete': 'C', 'CONCRETE': 'C', 'Steel': 'S', 'STEEL': 'S'}
for i in range(len(my_list)):
for k, v in search_strings.items():
if k.lower() in my_list[i].lower():
my_list[i] = v
break # avoids completing the loop if first item is found
print(my_list)
The result is
['S', 'C', 'Nothinginhere', '45', '56', 'S', 'C']
for m in MyList :
for k in SearchStrings :
if k.lower() in m.lower() :
print 'found', k, 'in', m, 'result', SearchStrings[k]
All the questions I've seen do the exact opposite of what I want to do:
Say I have a list:
lst = ['a','b','c']
I am looking to make a dictionary where the key is the element number (starting with 1 instead of 0) and the list element is the value. Like this:
{1:'a', 2:'b', 3:'c'}
But for a long list. I've read a little about enumerate() but everything I've seen has used the list element as the key instead.
I found this:
dict = {tuple(key): idx for idx, key in enumerate(lst)}
But that produces:
{'a':1, 'b':2, 'c':3}
... which is the opposite of what I want. And, also in a weird notation that is confusing to someone new to Python.
Advice is much appreciated! Thanks!
enumerate has a start keyword argument so you can count from whatever number you want. Then just pass that to dict
dict(enumerate(lst, start=1))
You could also write a dictionary comprehension
{index: x for index, x in enumerate(lst, start=1)}
By default enumerate start from 0 , but you can set by this value by second argument which is start , You can add +1 to every iterator if you want to start from 1 instead of zero :
print({index+1:value for index,value in enumerate(lst)})
output:
{1: 'a', 2: 'b', 3: 'c'}
Above dict comprehension is same as :
dict_1={}
for index,value in enumerate(lst):
dict_1[index+1]=value
print(dict_1)
Using Dict Comprehension and enumerate
print({x:y for x,y in enumerate(lst,1)})
{1: 'a', 2: 'b', 3: 'c'}
Using Dict Comprehension , zip and range-
print({x:y for x,y in zip(range(1,len(lst)+1),lst)})
{1: 'a', 2: 'b', 3: 'c'}
I think the below code should help.
my_list = ['A', 'B', 'C', 'D']
my_index = []
my_dict = {}
for i in range(len(my_list)):
my_index.append(i+1)
for key in my_index:
for value in my_list:
my_dict[key] = value
I have a single dictionary that contains four keys each key representing a file name and the values is nested lists as can be seen below:
{'file1': [[['1', '909238', '.', 'G', 'C', '131', '.', 'DP=11;VDB=3.108943e02;RPB=3.171491e-01;AF1=0.5;AC1=1;DP4=4,1,3,3;MQ=50;FQ=104;PV4=0.55,0.29,1,0.17', 'GT:PL:GQ', '0/1:161,0,131:99'], ['1', '909309', '.', 'T', 'C', '79', '.', 'DP=9;VDB=8.191851e-02;RPB=4.748531e-01;AF1=0.5;AC1=1;DP4=5,0,1,3;MQ=50;FQ=81.7;PV4=0.048,0.12,1,1', 'GT:PL:GQ', '0/1:109,0,120:99']......,'008_NTtrfiltered': [[['1', '949608', '.', 'G', 'A',...}
My question is how to check only the first two elements in the list for instance "1", "909238" for each of the key if they are the same and then write them to a file. The reason I want to do this is I want to filter only common values (only the first two elements of the list) for the four files (keys).
Thanks a lot in advance
Best.
You can access to the keys of the dictionary dictio and make your comparison using :
f = open('file.txt','w')
value_to_check_1 = '1'
value_to_check_2 = '909238'
for k in dictio:
value_1 = dictio[k][0][0][0]
value_2 = dictio[k][0][0][1]
if (( value_1 == value_to_check_1) and (value_2 == value_to_check_2)):
f.write('What you want to write\n')
f.close()
If you want to do a check that imply every values of your dictionary dictio.
Maybe you want to store couples of values from dictio.
couples = [(dictio[k][0][0][0], dictio[k][0][0][1]) for k in dictio]
Then, you can do a loop and iterate over the couples to do your check.
Example you can adapt according to your need :
for e in values_to_check:
for c in couples:
if (float(e[0][0][0]) >= float(c[0]) and float(e[0][0][1]) <= float(c[1])):
f.write(str(e[0][0][0]) + str(e[0][0][1]) + '\n')
I am writing a python program where I will be appending numbers into a list, but I don't want the numbers in the list to repeat. So how do I check if a number is already in the list before I do list.append()?
You could do
if item not in mylist:
mylist.append(item)
But you should really use a set, like this :
myset = set()
myset.add(item)
EDIT: If order is important but your list is very big, you should probably use both a list and a set, like so:
mylist = []
myset = set()
for item in ...:
if item not in myset:
mylist.append(item)
myset.add(item)
This way, you get fast lookup for element existence, but you keep your ordering. If you use the naive solution, you will get O(n) performance for the lookup, and that can be bad if your list is big
Or, as #larsman pointed out, you can use OrderedDict to the same effect:
from collections import OrderedDict
mydict = OrderedDict()
for item in ...:
mydict[item] = True
If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -
>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])
If order is a matter of concern, then you can use: -
>>> def addUnique(l, num):
... if num not in l:
... l.append(num)
...
... return l
You can also find an OrderedSet recipe, which is referred to in Python Documentation
If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.
s = set()
if number1 not in s:
s.add(number1)
if number2 not in s:
s.add(number2)
...
s = sorted(s) #Now a list in ascending order
You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.
To check if a number is in a list one can use the in keyword.
Let's create a list
exampleList = [1, 2, 3, 4, 5]
Now let's see if it contains the number 4:
contains = 4 in exampleList
print(contains)
>>>> True
As you want to append when an element is not in a list, the not in can also help
exampleList2 = ["a", "b", "c", "d", "e"]
notcontain = "e" not in exampleList2
print(notcontain)
>>> False
But, as others have mentioned, you may want to consider using a different data structure, more specifically, set. See examples below (Source):
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
'orange' in basket # fast membership testing
True
'crabgrass' in basket
False
# Demonstrate set operations on unique letters from two words
...
a = set('abracadabra')
b = set('alacazam')
a # unique letters in a
>>> {'a', 'r', 'b', 'c', 'd'}
a - b # letters in a but not in b
>>> {'r', 'd', 'b'}
a | b # letters in a or b or both
>>> {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b # letters in both a and b
>>> {'a', 'c'}
a ^ b # letters in a or b but not both
>>> {'r', 'd', 'b', 'm', 'z', 'l'}