Convert a list into a dictionary of list in Python - python

I need to convert a list into a dictionary in Python.
The list is:
list = [['a','aa','aaa'],['b','bb','bbb']]
And I want to convert it to a dictionary such that:
dictionary = {'aaa': ['a','aa'], 'bbb': ['b','bb']]
I'm looking for a variant of:
d = {i:j for i,j in list}
Thanks in advance!.

With list slicing, where [-1] grabs the last element of the list, and [:-1] grabs all elements up to the last:
Try refraining from using list as a variable name, since it is a built-in type:
d = {x[-1]: x[:-1] for x in lst}

Related

Find a value of Key in Json Array - Python

I have a Json array which has key value pairs. I want to get value of a particular key in the list. I don't know at what position the key will be in the array so I cant use the index in the array.
How can I get this please? I have tried something like below code to get value of 'filterB' which is 'val1' but no luck. Thanks.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
w = y['filters']['filterB']
print (w)
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension

How do I save changes made in a dictionary values to itself?

I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])

How to add to dictionary from input

I'm just starting out at Python and need some help with dictionaries. I'm looking to add keys to a dictionary based on input that is a list with string elements:
Ex.
x = {}
a = ['1', 'line', '56_09', '..xxx..']
Now say a while loop has come to this list a. I try to add to the dictionary with this code:
if a[1] == 'line':
x[a[2]] = [a[-1]]
I want the dictionary to read x = { '56_09': '..xxx..'} and want to confirm that by printing it. Do i need to adjust the elements on the list to strings or is it something with the if statement that I need to change?
The one problem with your code is in the if block:
if a[1] == 'line':
x[a[2]] = [a[-1]]
Instead, it should be like this:
if a[1] == 'line':
x[a[2]] = a[-1]
What you did was creating a list with one element: the last element of the list a.
you can make a dict object form two lists using ZIP and dict()
dict(zip(list1,list2)).
I believe for your question make two list form the input list based on the requirement and use above syntax.
I think you need something like this : -
def check(x,a):
if 'line' in a[1]:
x[a[2]] = a[-1]
return x
After
check({},['1', 'line', '56_09', '..xxx..'])
if a[1]=='line':
x={a[2]:a[-1]}
dictionary comprehension Create a dictionary with list comprehension in Python
{r:"test" for r in range(10)}

How can I check if a list exist in a dictionary of lists in the same order

Say I have a dictionary of lists,
C = {}
li = []
li.append(x)
C[ind] = li
And I want to check if another list is a member of this dictionary.
for s in C.values():
s.append(w)
Python checks it for any occurrences of the values in s and the dictionary values. But I want to check if any of the lists in the dictionary is identical to the given list.
How can I do it?
Use any for a list of lists:
d = {1 : [1,2,3], 2: [2,1]}
lsts = [[1,2],[2,1]]
print(any(x in d.values() for x in lsts))
True
d = {1:[1,2,3],2:[1,2]}
lsts = [[3,2,1],[2,1]]
print(any(x in d.values() for x in lsts))
False
Or in for a single list:
lst = [1,2]
lst in d.itervalues()
Python will compare each element of both lists so they will have to have the same order to be equal, even if they have the same elements inside the order must also be the same so a simple comparison will do what you want.
in does the trick perfectly, because it does a comparison with each element behind the scenes, so it works even for mutable elements:
lst in d.values()

Find out if no items in a list are keys in a dictionary

I have this list:
source = ['sourceid', 'SubSourcePontiflex', 'acq_source', 'OptInSource', 'source',
'SourceID', 'Sub-Source', 'SubSource', 'LeadSource_295', 'Source',
'SourceCode', 'source_code', 'SourceSubID']
I am iterating over XML in python to create a dictionary for each child node. The dictionary varies in length and keys with each iteration. Sometimes the dictionary will contain a key that is also an item in this list. Sometimes it wont. What I want to be able to do is, if a key in the dictionary is also an item in this list then append the value to a new list. If none of the keys in the dictionary are in list source, I'd like to append a default value. I'm really having a brain block on how to do this. Any help would be appreciated.
Just use the in keyword to check for membership of some key in a dictionary.
The following example will print [3, 1] since 3 and 1 are keys in the dictionary and also elements of the list.
someList = [8, 9, 7, 3, 1]
someDict = {1:2, 2:3, 3:4, 4:5, 5:6}
intersection = [i for i in someList if i in someDict]
print(intersection)
You can just check if this intersection list is empty at every iteration. If the list is empty then you know that no items in the list are keys in the dictionary.
in_source_and_dict = set(mydict.keys()).intersection(set(source))
in_dict_not_source = set(mydict.keys()) - set(source)
in_source_not_dict = set(source) - set(mydict.keys())
Iterate over the result of which one you want. In this case I guess you'll want to iterate over in_source_not_dict to provide default values.
In Python 3, you can perform set operations directly on the object returned by dict.keys():
in_source_and_dict = mydict.keys() & source
in_dict_not_source = mydict.keys() - source
in_source_not_dict = source - mydict.keys()
This will also work in Python 2.7 if you replace .keys() by .viewkeys().
my_dict = { some values }
values = []
for s in sources:
if my_dict.get(s):
values += [s]
if not values:
values += [default]
You can loop through the sources array and see if there is a value for that source in the dictionary. If there is, append it to values. After that loop, if values is empty, append the default vaule.
Note, if you have a key, value pair in your dictionary (val, None) then you will not append the None value to the end of the list. If that is an issue you will probably not want to use this solution.
You can do this with the any() function
dict = {...}
keys = [...]
if not any(key in dict for key in keys):
# no keys here
Equivalently, with all() (DeMorgan's laws):
if all(key not in dict for key in keys):
# no keys here

Categories

Resources