How to convert List in to Dictionary in python? - python

I have a list like this :
list1 = ["a:b","x:y","s:e","w:x"]
I want convert into dictionary like this:
dict = {'a':'b', 'x':'y','s':'e','w':'x'}
The list is dynamic. How could i achieve this ?

You could do
>>> list1 = ["a:b","x:y","s:e","w:x"]
>>> dict(elem.split(':') for elem in list1)
{'a': 'b', 'x': 'y', 's': 'e', 'w': 'x'}

Like this?
super_dict = dict()
for el in list1:
super_dict[el[0]] = el[-1]
Of course there could be problems if the keys are identical, you'll need to add code if needed

Related

Python: Create dictionary with list index number as key and list element as value?

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

list comprehension using dictionary entries

trying to figure out how I might be able to use list comprehension for the following:
I have a dictionary:
dict = {}
dict ['one'] = {"tag":"A"}
dict ['two'] = {"tag":"B"}
dict ['three'] = {"tag":"C"}
and I would like to create a list (let's call it "list") which is populated by each of the "tag" values of each key, i.e.
['A', 'B', 'C']
is there an efficient way to do this using list comprehension? i was thinking something like:
list = [x for x in dict[x]["tag"]]
but obviously this doesn't quite work. any help appreciated!
This is an extra step but gets the desired output and avoids using reserved words:
d = {}
d['one'] = {"tag":"A"}
d['two'] = {"tag":"B"}
d['three'] = {"tag":"C"}
new_list = []
for k in ('one', 'two', 'three'):
new_list += [x for x in d[k]["tag"]]
print(new_list)
Try this:
d = {'one': {'tag': 'A'},
'two': {'tag': 'B'},
'three': {'tag': 'C'}}
tag_values = [d[i][j] for i in d for j in d[i]]
>>> print tag_values
['C', 'B', 'A']
You can sort the list afterwards if it matters.
If you have other key/value pairs in the inner dicts, apart from 'tag', you may want to specify the 'tag' keys, like this:
tag_value = [d[i]['tag'] for i in d if 'tag' in d[i]]
for the same result. If 'tag' is definitely always there, remove the if 'tag' in d[i] part.
As a side note, never a good idea to call a list 'list', since it's a reserved word in Python.
You can try this:
[i['tag'] for i in dict.values()]
I would do something like this:
untransformed = {
'one': {'tag': 'A'},
'two': {'tag': 'B'},
'three': {'tag': 'C'},
'four': 'bad'
}
transformed = [value.get('tag') for key,value in untransformed.items() if isinstance(value, dict) and 'tag' in value]
It also sounds like you're trying to get some info out of JSON you might want to look into a tool like https://stedolan.github.io/jq/manual/

If variable is equal to any value in a list

I want to make a IF statement inside a for loop, that I want it to be triggered if the variable is equal to any value in the list.
Sample data:
list = [variable1, variable2, variable3]
Right now I have this sample code:
for k, v in result_dict.items():
if k == 'varible1' or k == 'variable2' or k == 'variable2':
But the problem is the list will grow larger and I don't to have to create multiple OR statements for every variable.
how can I do it?
This is what the in operator is for. Do:
list = [variable1, variable2, variable3]
for k, v in result_dict.items():
if k in list:
Another way to do it is with sets:
>>> l = ['a', 'b', 'c']
>>> d = {'a': 1, 'b': 2, 'c': 'three', 'd': 4, 'e': 5, 'f': 6}
>>> keys = set(l).intersection(d.keys())
>>> keys
set(['a', 'c', 'b'])
Then you can iterate over those keys:
for k in set(l).intersection(d.keys()):
do_something(d[k])
This should be more efficient than repetitively calling in on the list. Call set() on the shortest of the list or dictionary.
You may need another FOR loop.
for k, v in result_dict.items():
for i in list:
if i==k:

What is the best way to search for a key in multiple dictionaries in Python

I know we can search for a key in Python like this:
if key in myDict:
#Do something here
I know we can extend this and search for the key in multiple dictionaries using elif statement
if key in myDict_1:
#Do something here
elif key in myDict_2:
#Do something here
or by doing
if key in (myDict_1.keys() + myDict_2.keys()):
#Do something here
But is there a more succinct way to search for key in Python in two different dicts without using if-else or adding the list of keys explicitly ?
The answer to your question as written is:
if any(key in d for d in dicts):
# do something
If you need to know which dictionary or dictionaries contain the key, you can use itertools.compress():
>>> d1 = dict(zip("kapow", "squee"))
>>> d2 = dict(zip("bar", "foo"))
>>> d3 = dict(zip("xyz", "abc"))
>>> dicts = d1, d2, d3
>>> from pprint import pprint
>>> pprint(dicts)
({'a': 'q', 'k': 's', 'o': 'e', 'p': 'u', 'w': 'e'},
{'a': 'o', 'b': 'f', 'r': 'o'},
{'x': 'a', 'y': 'b', 'z': 'c'})
>>> from itertools import compress
>>> for d_with_key in compress(dicts, ("a" in d for d in dicts)):
... print(d_with_key)
...
{'a': 'q', 'p': 'u', 'k': 's', 'w': 'e', 'o': 'e'}
{'a': 'o', 'r': 'o', 'b': 'f'}
The correct way would be as Zero wrote:
if any(key in d for d in dicts): # do something
Fixing after reading comments below, thanks to #jwodder:
But you can also create a tuple of the keys of both (or more) dictionaries using the itertools.chain function.
>>> a = {1:2}
>>> b = {3:4}
>>> c = {5:6, 7:8}
>>> print(tuple(itertools.chain(a, b, c)))
(1, 3, 5, 7)
so you also can :
if x in tuple(itertools.chain(a, b, c)):
# Do something
A little list comprehension is also possible here; if you're simply trying to ascertain if a key is in a container of dicts, any() does exactly that; if you want to get the dict (or dicts) back and work with them, perhaps something like this would suffice:
>>> def get_dicts_with_key(some_key, *dicts):
... return [d for d in dicts if some_key in d]
>>> dict1 = {"hey":123}
>>> dict2 = {"wait":456}
>>> get_dicts_with_key('hey', dict1, dict2)
[{'hey': 123}]
>>> get_dicts_with_key('wait', dict1, dict2)
[{'wait': 456}]
>>> get_dicts_with_key('complaint', dict1, dict2)
[]
If the keys were present in either dict, both would be returned, as such:
>>> dict1['complaint'] = 777
>>> dict2['complaint'] = 888
>>> get_dicts_with_key('complaint', dict1, dict2)
[{'complaint': 777, 'hey': 123}, {'complaint': 888, 'wait': 456}]
>>>
Why don't you put your dicts in an iterable like a list and simple loop over then? You can express it as a function like so.
def has_key(key, my_dicts):
for my_dict in my_dicts:
if key in my_dict:
return True
return False
It would be used like so.
>>> dict1 = {'a':1, 'b': 2}
>>> dict2 = {'b':10, 'c': 11}
>>> has_key('b', [dict1, dict2])
True

Sort a dictionary alphabetically, and print it by frequency

I am running python 2.7.2 on a mac.
I have a simple dictionary:
dictionary= {a,b,c,a,a,b,b,b,b,c,a,w,w,p,r}
I want it to be printed and have the output like this:
Dictionary in alphabetical order:
a 4
b 5
c 2
p 1
r 1
w 2
But what I'm getting is something like this...
a 1
a 1
a 1
a 1
b 1
.
.
.
w 1
This is the code I am using.
new_dict = []
for word in dictionary.keys():
value = dictionary[word]
string_val = str(value)
new_dict.append(word + ": " + string_val)
sorted_dictionary = sorted(new_dict)
for entry in sorted_dictionary:
print entry
Can you please tell me where is the mistake?
(By the way, I'm not a programmer but a linguist, so please go easy on me.)
What you're using is not a dictionary, it's a set! :)
And sets doesn't allow duplicates.
What you probably need is not dictionaries, but lists.
A little explanation
Dictionaries have keys, and each unique keys have their own values:
my_dict = {1:'a', 2:'b', 3:'c'}
You retrieve values by using the keys:
>>> my_dict [1]
'a'
On the other hand, a list doesn't have keys.
my_list = ['a','b','c']
And you retrieve the values using their index:
>>> my_list[1]
'b'
Keep in mind that indices starts counting from zero, not 1.
Solving The Problem
Now, for your problem. First, store the characters as a list:
l = ['a', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'a', 'w', 'w', 'p', 'r']
Next, we'll need to know what items are in this list:
items = []
for item in l:
if item not in items:
items.append(item)
This is pretty much equal to items = set(l) (the only difference is that this is a list). But just to make things clear, hope you understand what the code does.
Here is the content of items:
>>> items
['a', 'b', 'c', 'w', 'p', 'r']
With that done, we will use lst.count() method to see the number of a char's occurence in your list, and the built-in function sorted() to sort the items:
for item in sorted(items): #iterates through the sorted items.
print item, l.count(item)
Result:
a 4
b 5
c 2
w 2
p 1
r 1
Hope this helps!!
Let's start with the obvious, this:
dictionary= {a,b,c,a,a,b,b,b,b,c,a,w,w,p,r}
is not a dictionary. It is a set, and sets do not preserve duplicates. You probably meant to declare that as a list or a tuple.
Now, onto the meat of your problem: you need to implement something to count the items of your collection. Your implementation doesn't really do that. You could roll your own, but really you should use a Counter:
my_list = ['a','b','c','a','a','b','b','b','b','c','a','w','w','p','r']
from collections import Counter
c = Counter(my_list)
c
Out[19]: Counter({'b': 5, 'a': 4, 'c': 2, 'w': 2, 'p': 1, 'r': 1})
Now on to your next problem: dictionaries (of all types, including Counter objects) do not preserve key order. You need to call sorted on the dict's items(), which is a list of tuples, then iterate over that to do your printing.
for k,v in sorted(c.items()):
print('{}: {}'.format(k,v))
a: 4
b: 5
c: 2
p: 1
r: 1
w: 2
dictionary is something like this{key1:content1, key2:content2, ...} key in a dictionary is unique. then a = {1,2,3,4,5,5,4,5,6} is the set, when you print this out, you will notice that
print a
set([1,2,3,4,5,6])
duplicates are eliminated.
In your case, a better data structure you can use is a list which can hold multiple duplicates inside.
if you want to count the element number inside, a better option is collections.Counter, for instance:
import collections as c
cnt = c.Counter()
dict= ['a','b','c','a','a','b','b','b','b','c','a','w','w','p','r']
for item in dict:
cnt[item]+=1
print cnt
the results would be:
Counter({'b': 5, 'a': 4, 'c': 2, 'w': 2, 'p': 1, 'r': 1})
as you notice, the results become a dictionary here.
so by using:
for key in cnt.keys():
print key, cnt[key]
you can access the key and content
a 4
c 2
b 5
p 1
r 1
w 2
you can achieve what you want by modifying this a little bit. hope this is helpful
Dictionary cannot be defined as {'a','b'}. If it defined so, then it is an set, where you can't find duplicates in the list
If your defining a character, give it in quotes unless it is declared already.
You can't loop through like this for word in dictionary.keys():, since here dictionary is not a dictionary type.
If you like to write a code without using any builtin function, try this
input=['a','b','c','a','a','b','b','b','b','c','a','w','w','p','r']
dict={}
for x in input:
if x in dict.keys():
dict[x]=dict[x]+1
else:
dict[x]=1
for k in dict.keys():
print k, dict[k]
First, a dictionary is an unordered collection (i.e., it has no guaranteed order of its keys).
Second, each dict key must be unique.
Though you could count the frequency of characters using a dict, there's a better the solution. The Counter class in Python's collections module is based on a dict and is specifically designed for a task like tallying frequency.
from collections import Counter
letters = ['a', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'a', 'w', 'w', 'p', 'r']
cnt = Counter(letters)
print cnt
The contents of the counter are now:
Counter({'b': 5, 'a': 4, 'c': 2, 'w': 2, 'p': 1, 'r': 1})
You can print these conveniently:
for char, freq in sorted(cnt.items()):
print char, freq
which gives:
a 4
b 5
c 2
p 1
r 1
w 2

Categories